Match a pattern only once

wawiwa picture wawiwa · Mar 13, 2013 · Viewed 38.3k times · Source

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?

Answer

Hugo Dozois picture Hugo Dozois · Mar 13, 2013

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.