英文:
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 <- Should match and return 'sometext' in a group
_foobar.txt <--- I want it to NOT match on this
.foobar.txt <---- Works match group (foobar)
.bcd_foobar.txt <---- 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$
Note that you have 2 capture groups, if you want a match only:
^\.?(?:[a-zA-Z0-9]+_)?foobar\.txt$
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论