我尝试使用 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)
拜托,有人可以帮我正确的正则表达式模式吗?
最佳答案
您可以使用
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 组的内容。
关于r - 如何通过R的逆模式提取子串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46951960/