Get the first word of a string using RegEx

I am trying to match the first word in a string with RegEx.

I know how to match the 1st word if the 1st character string is a word, but the problem is when my line starts; eg.

^([\w\-]+)

Works with

This is my sentence.

but not with

; This is my sentence

My goal is to combine the 1st word

This

No matter what character before.

Thank.

+3
source share
4 answers

You should use this:

\b([\w-]+)\b

Anchor ^is a problem that forces you to match words only when begging. This should be replaced by \b(word boundary).

+2
source

Try this template:

^\W*([\w-]+)

(^) - (\W*) , (([\w-]+)).

+4

If your language supports lookbehind

(?<=^\W*?)([\w\-]+)

will only fit what you need without playing with groups

Otherwise, Marius Schulz’s answer will do the job!

+3
source

Try this link http://www.regular-expressions.info/wordboundaries.html There is something called word boundaries in regex

-1
source

All Articles