我正在使用R语言处理文本,对于某些特定的提取需求,我需要使用捕获组。但出于某种原因,我熟悉的基础/stringr函数似乎不支持捕获组:
str_extract("abcd123asdc", pattern = "([0-9]{3}).+$")
# Returns: "123asdc"
stri_extract(str = "abcd123asdc", regex = "([0-9]{3}).+$")
# Returns: "123asdc"
grep(x = "abcd123asdc", pattern = "([0-9]{3}).+$", value = TRUE)
# Returns: "abcd123asdc"
常规的“R捕获组正则表达式”谷歌搜索没有提供有用的解决方案。我是错过了什么,还是在R中未实现捕获组? 编辑:尝试评论中提出的解决方案后,它适用于小例子,但对于我的情况失败了。 请注意,这是来自enron电子邮件数据集的文本,不包含敏感信息。
txt <- "Message-ID: <24216240.1075855687451.JavaMail.evans@thyme>
Date: Wed, 18 Oct 2000 03:00:00 -0700 (PDT)
From: phillip.allen@enron.com
To: leah.arsdall@enron.com
Subject: Re: test
Mime-Version: 1.0
Content-Type: text/plain; charset=us-ascii
Content-Transfer-Encoding: 7bit
X-From: Phillip K Allen
X-To: Leah Van Arsdall
X-cc:
X-bcc:
X-Folder: \\Phillip_Allen_Dec2000\\Notes Folders\\sent mail
X-Origin: Allen-P
X-FileName: pallen.nsf
test successful. way to go!!!"
sub("X-FileName:.+\n\n([\\W\\w]+)$", "\\1", txt)
# Returns all of "txt", not the capture group
由于我们只有一个捕获组,应该用"\1"来捕获它,我已经在在线正则表达式测试器上测试过了,应该可以工作。也尝试使用\n和\n来表示换行符。有什么想法吗?
sub(".*([0-9]{3}.+$)", "\\1", "abcd123asdc")
可能会返回:123asdc
- David Arenburggregexpr
。 - David Arenburg\P
和\N
是未知的转义序列,反斜杠必须加倍。 - Wiktor Stribiżewregmatches
用于在 R 中仅提取匹配项,与g/regexpr
和regexec
结合使用。它在?grep
的“另请参阅”部分中列出并描述 - 帮助文件总是值得一读的。 - thelatemail