R相当于Python的re.findall

rub*_*bik 5 python regex r

我试图从一个字符串中获取RegExp的所有匹配,但显然它在R中并不那么容易,或者我忽略了一些东西.说实话,这真的令人困惑,我发现自己所有的选项中迷失:str_extract,str_match,str_match_all,regexec,grep,gregexpr,谁知道有多少人.

实际上,我想要完成的只是(在Python中):

>>> import re
>>> re.findall(r'([\w\']+|[.,;:?!])', 'This is starting to get really, really annoying!!')
['This', 'is', 'starting', 'to', 'get', 'really', ',', 'really', 'annoying', '!', '!']
Run Code Online (Sandbox Code Playgroud)

上面提到的功能的问题是它们返回一个匹配,或者它们根本不返回匹配.

Wik*_*żew 5

通常,没有R完全等效于Python re.findall,它返回一个匹配值列表或(一个列表)包含捕获组子匹配的元组.最接近str_match_allstringr包,但它也非常接近Python re.finditer(因为它返回第一项中的匹配值,然后返回后续项中的所有子匹配(捕获组内容)(仍然不完全等同re.finditer于仅文本)返回,不匹配数据对象)).因此,如果未返回整个匹配值str_match_all,则它将与Python完全等效re.findall.

re.findall只是为了返回匹配而不是捕获,模式中的捕获组是多余的,您可以将其删除.因此,你可以放心地使用regmatchesgregexpr和PCRE的味道(因为[\\w']不会用正则表达式TRE工作):

s <- "This is starting to get really, really annoying!!"
res <- regmatches(s, gregexpr("[\\w']+|[.,;:?!]", s, perl=TRUE))
## => [[1]]
[1] "This"     "is"      "starting" "to"       "get"      "really"  
[7] ","        "really"   "annoying" "!"        "!"  
Run Code Online (Sandbox Code Playgroud)

参见R演示

或者,为了使\wUnicode识别,使其像在Python 3中一样工作,添加(*UCP)PCRE动词:

res <- regmatches(s, gregexpr("(*UCP)[\\w']+|[.,;:?!]", s, perl=TRUE))
Run Code Online (Sandbox Code Playgroud)

另一个R演示

如果你想使用stringr包(在幕后使用ICU正则表达式库),你需要str_extract_all:

res <- str_extract_all(s, "[\\w']+|[.,;:?!]")
Run Code Online (Sandbox Code Playgroud)