Match a pattern only once

删除回忆录丶 提交于 2021-01-27 04:14:17

问题


I have a string

foo-bar-bat.bla

I wish to match only foo

My flawed pattern matches both foo and bar

\w+(?=-.*\.bla)

How do I discard bar? Or maybe even better, how could I stop matching stuff after foo?


回答1:


You could use the following pattern (as long as your strings are always formatted the way you said) :

^\w+(?=-.*\.bla)

Regular expression image

Edit live on 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.




回答2:


^[^-]+

The starting ^ means to start matching from the beginning of the string. The charactergroup [^-] means to search for anything that is not a dash. The + means that the charactergroup should be match a character one or multiple times.




回答3:


The ".*" part of your expression matches "bar."

^\w+(?=-.*)

This expression reads as "At the start of a string, at least one character followed by (but not includeded in the match) a DASH followed by anything"

^ \w+ (?=-.*)
|  |    |
|  |   matches "-bar-bat.bla"
|  matches "foo"
start of string


来源:https://stackoverflow.com/questions/15392753/match-a-pattern-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!