正则表达式匹配在第一组中出错

huangapple go评论67阅读模式
英文:

regex match getting wrong in group 1

问题

我有一个字符串,我需要这种模式 $body.anyname 或者 $body.anyname.anyname,但不要像这样 $body.anyname.
我写了这个正则表达式 \$[body](\w+((\[\d\]){0,}\.\w+(\[\d\]){0,}){0,}) 它匹配整个字符串,但我需要将 body.anyname 提取到第1组中,而实际上得到的是 ody.anyname。这可以通过字符串操作来实现,但由于某些原因我需要使用正则表达式。在这里检查正则表达式 <https://regex101.com/r/PigNVO/1/>。

英文:

I have a string and I need this pattern $body.anyname or $body.anyname.anyname or like this, but not like $body.anyname.
I wrote this regex \$[body](\w+((\[\d\]){0,}\.\w+(\[\d\]){0,}){0,}) its matching the whole string but I need the body.anyname in group 1, but getting ody.anyname This can be done by string manipulation but for some reason I need to use regex. Check the regex here <https://regex101.com/r/PigNVO/1/>

答案1

得分: 1

你可以在右边使用断言来排除点之前的空白边界。

请注意,这部分 [body] 是一个字符类,可以匹配 body 中的任意一个,并且不是第一个组的一部分。

$(body(?:\.\w+)+)(?!\S)

分解:

  • \$ 匹配 $
  • ( 捕获组 1
  • body 字面匹配
    • (?:\.\w+)+ 重复1次或更多次,匹配一个点和1个或多个单词字符
  • ) 关闭捕获组 1
  • (?!\S) 断言右侧为空白边界

正则表达式演示链接

英文:

You could use and assertion for a whitespace boundary at the right to exclude the dot.

Note that this part [body] is character class that matches either b o d or y and is not part of the first group.

$(body(?:\.\w+)+)(?!\S)

In parts

  • \$ Match $
  • ( Capture group 1
  • body Match literally
    • (?:\.\w+)+ Repeat 1+ times matching a dot and 1+ word chars
  • ) Close group 1
  • (?!\S) Assert a whitespace boundary to the right

Regex demo

huangapple
  • 本文由 发表于 2020年6月29日 17:17:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/62634955.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定