R lookbehind断言中的正则表达式

问题描述 投票:2回答:2

我正在尝试与extracttidyr函数进行一些模式匹配。我在正则表达式练习网站上测试了我的正则表达式,模式似乎有用,我使用的是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,尽管已经在NA上测试了模式,但我的目标列是所有www.regexr.com值。根据文档,R模式匹配支持lookbehind断言,所以我不知道还有什么在这里做。

r regex lookbehind
2个回答
0
投票

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

你不必在这里使用lookbehind,因为如果在模式中使用捕获组,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]*

0
投票

我不确定外观部分,但在R中,你需要逃避反斜杠。如果您使用的是非特定于R的正则表达式检查程序,则这一点并不明显。

更多信息here

所以你可能希望你的正则表达式看起来像:

"attackLocationStartX,\\sValues\\s=\\s)[0-9.]+"
© www.soinside.com 2019 - 2024. All rights reserved.