繁体   English   中英

R背后的正则表达式断言

[英]Regex in R lookbehind assertion

我正在尝试使用tidyrextract函数进行一些模式匹配。 我已经在正则表达式练习站点中测试了我的正则表达式,该模式似乎可行,并且我在使用lookbehind assertion

我有以下示例文本:

=[\"{ Key = source, Values = web,videoTag,assist }\",\"{ Key = type, 
Values = attack }\",\"{ Key = team, Values = 2 }\",\"{ Key = 
originalStartTimeMs, Values = 56496 }\",\"{ Key = linkId, Values = 
1551292895649 }\",\"{ Key = playerJersey, Values = 8 }\",\"{ Key = 
attackLocationStartX, Values = 3.9375 }\",\"{ Key = 
attackLocationStartY, Values = 0.739376770538243 }\",\"{ Key = 
attackLocationStartDeflected, Values = false }\",\"{ Key = 
attackLocationEndX, Values = 1.7897727272727275 }\",\"{ Key = 
attackLocationEndY, Values = -1.3002832861189795 }\",\"{ Key = 
attackLocationEndDeflected, Values = false }\",\"{ Key = lastModified, 
Values = web,videoTag,assist 

我想抓住attackLocationX的数字(有关攻击位置的所有文本之后的所有数字。

但是,将以下代码与lookbehind断言一起使用时,没有任何结果:

df %>% 
extract(message, "x_start",'((?<=attackLocationStartX,/sValues/s=/s)[0- 
9.]+)')

如果未找到任何模式匹配,此函数将返回NA ,尽管我已经在www.regexr.com上测试了模式,但我的目标列是所有NA值。 根据文档, R模式匹配支持后置断言,因此我不确定在此还可以做什么。

我不确定后面的部分,但是在R中,您需要转义反斜杠。 如果您使用的不是R特定的正则表达式检查器,则这并不明显。

更多信息在这里

因此,您可能希望您的正则表达式看起来像:

"attackLocationStartX,\\sValues\\s=\\s)[0-9.]+"

首先,要匹配空白,您需要\\s ,而不是/s

您不必在此处使用后退,因为如果模式中使用了捕获组,则extract将返回捕获的子字符串。

采用

df %>% 
  extract(message, "x_start", "attackLocationStartX\\s*,\\s*Values\\s*=\\s*(-?\\d+\\.\\d+)")

输出: 3.9375

正则表达式也可能看起来像"attackLocationStartX\\\\s*,\\\\s*Values\\\\s*=\\\\s*(-?\\\\d[.0-9]*)"

由于捕获了(-?\\\\d+\\\\.\\\\d+)部分,因此只有该组中的文本才是输出。

图案细节

  • (-?\\d+\\.\\d+) -匹配的捕获组
    • -? -可选的连字符( ?表示1或0次出现
    • \\d+ -1或或数字( +表示1或更多
    • \\. -一个点
    • \\d+ -1或或数字
  • \\d[.0-9]* -一个数字( \\d ),后跟0个或多个点或数字( [.0-9]*

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM