0

I am trying to figure out how to use Regular Expressions to match a word in a sentence a maximum number of times.

Say I have this sentence: "This test sentence is for a test that I have to take, hope I ace this test"

Now say I want to search for the word "test" in this sentence and return a maximum of 2 matches (so I'd hope it just picks up the first and second match and gives up).

Here's what I've tried:

  1. /\btest\b/g - works great if I want all 3 occurrences of "test"
  2. /(\btest\b){0,2}/g - not sure why this doesn't work, I have grouped the word-boundary plus literal search term expression and have asked it to return 0 to 2.

Thanks in advance for any hints.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
  • What language are you using? There might be a better way to do this. For example in Python I would use `re.split()` to split the input string on word bounds then use `list.count()` to count how many times `'test'` occurs in the list. **Edit**: On second thought I would use something like `len(re.findall())` instead. – wjandrea Jun 15 '20 at 13:51
  • 1
    `\b` is a zero-width assertion, it does not match any text. `(\ba\b){2}` will never match anything. Use `.*` to allow any text between pattern parts. – Wiktor Stribiżew Jun 15 '20 at 13:53

0 Answers0