Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match first word in sentence

I am looking for a regex that matches first word in a sentence excluding punctuation and white space. For example: "This" in "This is a sentence." and "First" in "First, I would like to say \"Hello!\""

This doesn't work:

"""([A-Z].*?(?=^[A-Za-z]))""".r
like image 971
princess of persia Avatar asked Feb 08 '13 06:02

princess of persia


2 Answers

(?:^|(?:[.!?]\s))(\w+)

Will match the first word in every sentence.

http://rubular.com/r/rJtPbvUEwx

like image 148
endy Avatar answered Sep 19 '22 14:09

endy


You can use this regex: ^[^\s]+ or ^[^ ]+.

like image 31
Keon-Woong Moon Avatar answered Sep 16 '22 14:09

Keon-Woong Moon