有人告诉我 R 是一个很好的数据处理工具。所以我想弄清楚是否有可能(简单)使用 R 进行正则表达式数据提取。
下面是从 Python 中提取两个关键信息的示例:
import re
str = "oh, 100.0 dollar is 621.5 yuan"
m = re.search("([\d+\.\d+]+).*?([\d+\.\d+]+)",str)
if m:
print m.group(1),"->",m.group(2)
Python 的输出是:
100.0 -> 621.5
Python 的结果真的很酷,但如何在 R 中高效地完成它?
最佳答案
好吧,您的正则表达式不正确,但确实符合您的预期。 character class定义一组字符。说——“匹配类指定的一个字符”。
因此,它匹配以下内容:
[\d+\.\d+]+ # any character of: digits (0-9), '+', '\.', digits (0-9), '+'
# (1 or more times)
使用 base R,您可以使用具有以下模式的 regmatches
和 gregexpr
:
x <- 'oh, 100.0 dollar is 621.5 yuan'
m <- regmatches(x, gregexpr('\\d+(?:\\.\\d+)?', x, perl=T))[[1]]
paste(m[1], '->', m[2])
# [1] "100.0 -> 621.5"
正则表达式(解释)
\d+ # digits (0-9) (1 or more times)
(?: # group, but do not capture (optional):
\. # '.'
\d+ # digits (0-9) (1 or more times)
)? # end of grouping
关于python - R正则表达式从字符串中提取信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28037248/