Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/perl/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex 正则表达式获取某个字符前的单词_Regex_Perl_R - Fatal编程技术网

Regex 正则表达式获取某个字符前的单词

Regex 正则表达式获取某个字符前的单词,regex,perl,r,Regex,Perl,R,我需要在R中的字符串中的唯一字符(在我的例子中:&)前后获取单词 我需要从以下内容中获取“word1”: “…一些单词1和单词2一些…” 在R:(? 单词将在组1中捕获。这是包含在由两个边界包围的任何字符串中的不情愿匹配;在第二个边界为&后,如果使用(\S+)\S*&\S*(\S+)则将捕获&两侧的单词。这允许在符号和周围使用可选空格 您需要将R字符串中的反斜杠加倍,并使用regexec和regmatches函数应用模式并提取匹配的子字符串 string <- "...something

我需要在R中的字符串中的唯一字符(在我的例子中:&)前后获取单词

我需要从以下内容中获取“word1”: “…一些单词1和单词2一些…”

在R:
(?
单词将在组1中捕获。这是包含在由两个边界包围的任何字符串中的不情愿匹配;在第二个边界为
&

后,如果使用
(\S+)\S*&\S*(\S+)
则将捕获
&
两侧的单词。这允许在符号和周围使用可选空格

您需要将R字符串中的反斜杠加倍,并使用
regexec
regmatches
函数应用模式并提取匹配的子字符串

string  <- "...something something word1 & word2 something..."
pattern <- "(\\S+)\\s*&\\s*(\\S+)"
match   <- regexec(pattern, string)
words   <- regmatches(string, match)

string
(?可以使用中的
stripplyc
使用相对简单的正则表达式来完成。假设
s
是您的字符串:

library(gsubfn)
strapplyc(s, "(\\w+) & (\\w+)")

如果将来有人尝试类似的东西,最初这是可行的,但最终我遇到了这样的情况:出于某种原因,它抓住了多个单词。符号和周围的空白是唯一一致的条件之一,因此我最终使用:(?@GregS:我能想到的唯一原因是,如果您正在处理使用无中断空格
“\x{A0}”
的文本。您可以通过使用
([^\s\xA0]+)\s*&\s*([^\s\xA0]+)来解决这个问题
取而代之。请注意,这是Perl语法。我对R知之甚少,这可能是也可能不是使用其代码点添加字符的正确方法。第一个小写字母s需要一个双反斜杠,否则R将抛出一个错误。否则,这正是我需要的一个项目的答案!它在7年前的文章发表时确实有效。我已经将其替换为指向其CRAN页面的链接。
(?<=&)(\w*)(?=&)"
library(gsubfn)
strapplyc(s, "(\\w+) & (\\w+)")