I am trying to match the 1st word in a string with RegEx.
I know how to match the 1st word if the 1st chain of characters is a word, but the problem is when my string starts with ; for example.
^([\w\-]+)
Works with
This is my sentence.
but does not with
; This is my sentence
My goal is to match the 1st word
This
Independently which character(s) is before.
Thank you.
Try this pattern:
^\W*([\w-]+)
It is anchored at the beginning of the string (^
) and allows an arbitrary amount of leading non-word characters (\W*
) before the first word is matched in the pattern's first group (([\w-]+)
).
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