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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With