1
r'((?:\S+\s+){0,3}\bwhite\b\s*(?:\S+\s+){0,3})

The result of above regex for below sentence is

sentence = This is a white floral garment.
result = This is a white floral

But I want the result as

wanted result = This is a white floral garment

I want 3 words before and after the white word. If there are not three word after white than at least get all which are present there.

2

4 Answers 4

4

You can fix it by adding a word boundary \b to the subattern for words after white and making the space optional

((?:\S+\s+){0,3}\bwhite\b\s*(?:\S+\b\s*){0,3})

Demo

0

try this

((?:\S+\s+){3,}\bwhite\b\s*(?:\S+\b\s*){3,})

(?:\S+\s+){3,}\bwhite\b minimum 3 words before the word 'white'

s*(?:\S+\b\s*){3,} after minimum 3 word

Demo

0

Perhaps you could match one or more word characters \w+ followed by a whitespace character \s and repeat that 3 times {3} to match 3 words before the word "white".

Then match "white" and after that match a whitespace character and one or more times a word character and repeat that 0 - 3 times {0,3} so if there are 3 or less words following you would match that.

(?:\w+\s){3}white(?:\s\w+){0,3}

0

I used the above, but had issues if a comma came after the target word.

Playing around with the regex, this seemed to work on sentences like:

I want a white floral garment, etc.

((?:\S+\s+){0,3}\bwhite\b\w*(?:\W+\b\w*){0,3})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.