【问题标题】:How to extract a substring by inverse pattern with R?如何通过R的反向模式提取子字符串?
【发布时间】:2017-10-26 10:26:24
【问题描述】:

我尝试使用 gsub() R 函数按模式提取子字符串。

# Example: extracting "7 years" substring.
string <- "Psychologist - 7 years on the website, online"
gsub(pattern="[0-9]+\\s+\\w+", replacement="", string)`

`[1] "Psychologist -  on the website, online"

如您所见,使用 gsub() 很容易排除所需的子字符串,但我需要反转结果并仅获得“7 年”。 我考虑使用“^”,类似这样的:

gsub(pattern="[^[0-9]+\\s+\\w+]", replacement="", string)

拜托,谁能帮助我正确的正则表达式模式?

【问题讨论】:

  • 伙计们,你能解释一下为什么在 'replacement="\\1"' 中使用 "\\1" 吗?

标签: r regex string


【解决方案1】:

你可以使用

sub(pattern=".*?([0-9]+\\s+\\w+).*", replacement="\\1", string)

this R demo

详情

  • .*? - 任何 0+ 个字符,尽可能少
  • ([0-9]+\\s+\\w+) - 捕获组 1:
    • [0-9]+ - 一位或多位数字
    • \\s+ - 1 个或多个空格
    • \\w+ - 1 个或多个单词字符
  • .* - 字符串的其余部分(任何 0+ 个字符,尽可能多)

替换中的\1 替换为第 1 组的内容。

【讨论】:

  • 它工作正常。 “替换”参数中的“\\1”是什么意思?很抱歉第一次发表评论:)
  • @Michael 替换中的\1 替换为Group 1 的内容\1replacement backreference
【解决方案2】:

你可以使用\d的反义词,即R中的\D

string <- "Psychologist - 7 years on the website, online"
sub(pattern = "\\D*(\\d+\\s+\\w+).*", replacement = "\\1", string)
# [1] "7 years"

\D*的意思是:尽可能没有数字,其余的被捕获在一个组中,然后替换完整的字符串。

a demo on regex101.com

【讨论】:

  • 谢谢。很好的解决方案。
猜你喜欢
  • 2019-09-28
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-14
  • 1970-01-01
  • 1970-01-01
  • 2015-10-01
相关资源
最近更新 更多