Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.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
正则表达式字符串检测,除非使用R中的lookarounds检测到特定模式_R_Regex_Tidyverse_Regex Lookarounds_Stringr - Fatal编程技术网

正则表达式字符串检测,除非使用R中的lookarounds检测到特定模式

正则表达式字符串检测,除非使用R中的lookarounds检测到特定模式,r,regex,tidyverse,regex-lookarounds,stringr,R,Regex,Tidyverse,Regex Lookarounds,Stringr,我希望突出显示字符串中的一个模式,除非在以后的字符串处理中也使用regex检测到另一个模式。最后,我希望用空格替换所有hat或hats,除非在字符串中找到what或no,但在模式试验期间使用检测 数据: 其结果是: 最终结果应排除第六个字符串no-hat和第十一个字符串what,hat,no,hats,使其不被检测 我不确定我是否以正确的方式使用了lookarounds,或者我使用的regex函数是错误的。您可以使用以下ICU regex,前提是您在no和whatwords和hatword之间

我希望突出显示字符串中的一个模式,除非在以后的字符串处理中也使用regex检测到另一个模式。最后,我希望用
空格
替换所有
hat
hats
,除非在字符串中找到
what
no
,但在模式试验期间使用检测

数据:

其结果是:

最终结果应排除第六个字符串
no-hat
和第十一个字符串
what,hat,no,hats
,使其不被检测


我不确定我是否以正确的方式使用了lookarounds,或者我使用的
regex
函数是错误的。

您可以使用以下ICU regex,前提是您在
no
what
words和
hat
word之间不能有超过1K个字符:

stringr::str_replace_all(trial.string, 
      "(?i)(?<!\\b(?:no|what)\\b.{0,1000})\\bhats?(?!.*\\b(?:no|what)\\b)", " ")
输出:

[1] " "                   "coif"                " ter"               
 [4] " "                   "plushy"              "no hat"             
 [7] "what"                "hat no"              " "                  
[10] "HAT, what"           "what, hat, no, hats" "A water  "   

绳子有多长?如果它们不太长,可以使用
stringr::str_replace_all(trial.string),(?i)(?@Wiktor Stribiżew,look-behind断言中的量词?@Israel Girón-Palacios,似乎单个正则表达式不需要这样做。我建议另一种方法:用第一个正则表达式的“what”或“no”来筛选行(将它们保存在数组中,并替换为包含数组索引的转义序列),然后删除“hat”“使用第二个正则表达式,然后用第三个正则表达式解开屏蔽行。@AlexanderMashin是的,这在ICU正则表达式中是允许的。@WiktorStribiżew感谢您的跟进。由于我这边的一些情况,我现在只能快速浏览一下w
stru视图,但它似乎做得很好。谢谢。
stringr::str_replace_all(trial.string, 
      "(?i)(?<!\\b(?:no|what)\\b.{0,1000})\\bhats?(?!.*\\b(?:no|what)\\b)", " ")
trial.string<-c("Hat","coif","hatter","HATS","plushy","no hat","what","hat no","hats","HAT, what","what, hat, no, hats","A water hat")
stringr::str_replace_all(trial.string, 
      "(?i)(?<!\\b(?:no|what)\\b.{0,1000})\\bhats?(?!.*\\b(?:no|what)\\b)", " ")
[1] " "                   "coif"                " ter"               
 [4] " "                   "plushy"              "no hat"             
 [7] "what"                "hat no"              " "                  
[10] "HAT, what"           "what, hat, no, hats" "A water  "