本文介绍了只匹配一个模式一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个字符串
foo-bar-bat.bla我希望只匹配 foo
我有缺陷的模式同时匹配 foo 和 bar
My flawed pattern matches both foo and bar
\w+(?=-.*\.bla)如何丢弃 bar?或者甚至更好,我怎么能在 foo 之后停止匹配?
How do I discard bar? Or maybe even better, how could I stop matching stuff after foo?
推荐答案您可以使用以下模式(只要您的字符串始终按照您所说的方式格式化):
You could use the following pattern (as long as your strings are always formatted the way you said) :
^\w+(?=-.*\.bla)在 Debuggex 上实时编辑
^ 符号匹配字符串的开头.因此将采用字符串的第一个匹配项.
The ^ sign matches the beginning of the string. And thus will take the very first match of the string.
?= 是为了确保跟随的组未被捕获但存在.
The ?= is meant to make sure the group following is not captured but is present.
更多推荐
只匹配一个模式一次
发布评论