Giovanni
Giovanni

Reputation: 111

REGEX to extract string between spaces

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.

Upvotes: 4

Views: 25064

Answers (2)

Giovanni
Giovanni

Reputation: 111

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".

Upvotes: 7

Valdi_Bo
Valdi_Bo

Reputation: 31011

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.

Upvotes: 1

Related Questions