【问题标题】:Regex in R lookbehind assertionR 回溯断言中的正则表达式
【发布时间】:2019-03-21 13:47:23
【问题描述】:

我正在尝试使用来自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 后面的数字(关于攻击位置的任何文本后面的所有数字。

但是,使用带有后向断言的以下代码,我没有得到任何结果:

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

如果没有找到模式匹配,此函数将返回NA,并且我的目标列都是NA 值,尽管已经在www.regexr.com 上测试了模式。根据文档,R 模式匹配支持后向断言,所以我不确定这里还能做什么。

【问题讨论】:

  • 你为什么在后面看?看来您正在寻找 attackLocationStartX 之后的“值”。
  • 试试extract(message, "x_start", "attackLocationStartX\\s*,\\s*Values\\s*=\\s*(-?\\d+\\.\\d+)")。它提取3.9375。是预期的吗?还是您需要其他结果?
  • @WiktorStribiżew 这非常有效。 -? 是做什么的?我以前没见过。
  • -? 是一个可选的连字符。顺便说一句,我发了一个answer below

标签: r regex lookbehind


【解决方案1】:

首先,要匹配空格,您需要\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]*)

【讨论】:

    【解决方案2】:

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

    更多信息here

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-06
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2017-07-17
      • 1970-01-01
      相关资源
      最近更新 更多