英文:
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] 是一个字符类,可以匹配 b、o、d 或 y 中的任意一个,并且不是第一个组的一部分。
$(body(?:\.\w+)+)(?!\S)
分解:
\$匹配$(捕获组 1body字面匹配(?:\.\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 1bodyMatch literally(?:\.\w+)+Repeat 1+ times matching a dot and 1+ word chars
)Close group 1(?!\S)Assert a whitespace boundary to the right
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论