DeadDjangoDjoker DeadDjangoDjoker - 9 days ago 5
Python Question

python Regex to match sentences which has n words

Im looking for a python regex which matches sentences with 3 words before a string.

for example say i have sentence "this is the test" i want to match this one and only if there are any 3 words before the string test.

re.match(r'(\d\w+\d){3}test', "this is the test")


thought the above sentence would work but didnt work.

Answer
  • If you want to match strings with 3 words, separated by whitespace(s) followed by 'test': (\b){3}test
  • If you want to extract first 3 words, separated by whitespace(s) followed by 'test': (\w+\s+){3}test
  • If you want same thing, but want to allow whitespace(s) before the stopword: (\w+\s+){3}\w?test
  • If you want to do same, but with string ending with the stopword: (\w+\s+){3}\w?test$