Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REGEX to extract string between spaces

Tags:

regex

I'm new in regex, first time I use them. Given a string, with multiple words, I need to extract the second word (word = any number of char between to spaces).

For example: "hi baby you're my love"

I need to extract "baby"

I think I could start from this: (\b\w*\b) that matches every single word, but I don't know how to make it skip the first match.

like image 438
Giovanni Avatar asked Oct 31 '25 01:10

Giovanni


2 Answers

Thank's for suggestion guys, I've modified a little your regex and I finally find what I need:

(?<=\s)(.*?)(?=\s)

This one (?<=.)(\b\w+\b) was also kinda good but fails if I have string like "hi ba-by you're my love" splitting "ba-by" into "ba" and "by".

like image 94
Giovanni Avatar answered Nov 01 '25 18:11

Giovanni


You can do it even without \b. Use \w+\s+(\w+) and read the word from capturing group 1.

The regex above:

  • First mathes a non-empty sequence of word characters (the first word).
  • Then it matches a non-empty sequence of white chars (spaces) between word 1 and 2.
  • And finally, the capturing group captures just the second word.

Note that \s+(\w+) is wrong, because the source string can begin with a space and in such case this regex would have catched the first word.

like image 28
Valdi_Bo Avatar answered Nov 01 '25 19:11

Valdi_Bo