Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the 1st word of the string with RegEx

Tags:

regex

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.

like image 560
Milos Cuculovic Avatar asked Sep 06 '25 19:09

Milos Cuculovic


1 Answers

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-]+)).

like image 93
Marius Schulz Avatar answered Sep 08 '25 10:09

Marius Schulz