问题
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)
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