正则表达式 – 仅在零个或多个组匹配时匹配尾随字符

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

Regex - match trailing character only if zero or many group matches

问题

我无法弄清楚如何使我的正则表达式在零或多个组没有捕获任何内容的情况下不匹配。

我现在想出的正则表达式是:
```^\.?([a-zA-Z0-9]*)_?(foobar)\.txt$```

测试案例:

sometext_foobar.txt <- 应该匹配并在一个组中返回 'sometext'
_foobar.txt <--- 我希望它在这种情况下不匹配
.foobar.txt <---- 可以匹配组 (foobar)
.bcd_foobar.txt <---- 可以匹配组 (bcd) 和 (foobar)


基本上,如果 `([a-zA-Z0-9]*)` 不匹配,那么就不允许下划线。
英文:

I can't figure out how not have my regex match in the scenario where the zero or many group does not capture anything.

My regex I have come up with now
^\.?([a-zA-Z0-9]*)_?(foobar)\.txt$

Test cases:

sometext_foobar.txt &lt;- Should match and return &#39;sometext&#39; in a group
_foobar.txt      &lt;--- I want it to NOT match on this
.foobar.txt      &lt;---- Works match group (foobar)
.bcd_foobar.txt  &lt;---- Works match group (bcd) and (foobar)

Basically if ([a-zA-Z0-9]*) doesn't match, then do not allow an underscore.

答案1

得分: 3

你可以编写匹配1次或多次 [a-zA-Z0-9]+ 后跟下划线的模式,并使整个部分可选。

^.?([a-zA-Z0-9]+_)?(foobar).txt$

正则表达式演示

请注意,你有2个捕获组,如果你只想匹配:

^.?(?:[a-zA-Z0-9]+_)?foobar.txt$

正则表达式演示

英文:

You could write the pattern maching 1+ times [a-zA-Z0-9]+ followed by an underscore ,and make that whole part optional.

^\.?([a-zA-Z0-9]+_)?(foobar)\.txt$

Regex demo

Note that you have 2 capture groups, if you want a match only:

^\.?(?:[a-zA-Z0-9]+_)?foobar\.txt$

Regex demo

huangapple
  • 本文由 发表于 2023年6月29日 04:33:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76576536.html
匿名

发表评论

匿名网友

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

确定