python - R正则表达式从字符串中提取信息

标签 python regex r

有人告诉我 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,您可以使用具有以下模式的 regmatchesgregexpr:

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/

相关文章:

python - Pandas duplicated vs groupby 标记所有重复值

r - 垂直直方图

c++ - 在 MAC OSX 的同一个 R session 中调用两个 .Call (Rcpp) 函数

r - 如何 reshape 数据,使 R 中的行成为列?

python - 如何在 SQLAlchemy 中查看连接表的列名?

python - Matplotlib:双 y 轴图未对齐

python - 使用 SQLAlchemy 和 wxPython 的桌面应用程序的项目结构

regex - 正则表达式 - 不允许零

javascript - 需要替换变量值格式的正则表达式模式

php - 从下一个标签获取文本