murky123
murky123

Reputation: 120

Regex: Match word between 2 spaces on either side

This Regex is a bit niche and I'm really struggling to get it down. Here is an example of what I hope it would do:

      Testing      space was before this part word space after this part      this part      shouldn't count.

I want to try and extract all of the text between either of the two groups of spaces, this is what I've tried so far:

 {2}.*?word.*? {2}

(Not there is a space before both of the {2}'s)

It should only extract "space was before this part word space after this part". Any help would be appreciated, thanks!

Upvotes: 1

Views: 1269

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627545

You may use

 {2}(?:(?! {2}).)*?word.*? {2}

See the regex demo

Details

  • {2} - two spaces
  • (?:(?! {2}).)*? - any char other than line break chars, 0 or more times, but as few as possible, that does not start a two space character string
  • word - a word string
  • .*? - any 0+ chars other than line break chars, as few as possible
  • {2} - two spaces

Upvotes: 2

Related Questions