Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex get text before and after a hyphen

I have this string:

"Common Waxbill - Estrilda astrild"

How can I write 2 separate regexes for the words before and after the hyphen? The output I would want is:

"Common Waxbill" 

and

"Estrilda astrild"
like image 997
Oliver Oliver Avatar asked May 12 '16 15:05

Oliver Oliver


1 Answers

If you cannot use look-behinds, but your string is always in the same format and cannout contain more than the single hyphen, you could use

^[^-]*[^ -] for the first one and \w[^-]*$ for the second one (or [^ -][^-]*$ if the first non-space after the hyphen is not necessarily a word-character.

A little bit of explanation: ^[^-]*[^ -] matches the start of the string (anchor ^), followed by any amount of characters, that are not a hyphen and finally a character thats not hyphen or space (just to exclude the last space from the match).

[^ -][^-]*$ takes the same approach, but the other way around, first matching a character thats neither space nor hyphen, followed by any amount of characters, that are no hyphen and finally the end of the string (anchor $). \w[^-]*$ is basically the same, it uses a stricter \w instead of the [^ -]. This is again used to exclude the whitespace after the hyphen from the match.

like image 143
Sebastian Proske Avatar answered Sep 23 '22 11:09

Sebastian Proske