david-l
david-l

Reputation: 623

Start matching specific whole words after the first four characters are typed

The regex below matches the whole word service, generic, computer or master:

(?:^|(?<= ))(service|generic|computer|master)(?:(?= )|$)

I'd like it to match as soon as the first 4 characters are matched with the pattern.

Thank you in advance.

Upvotes: 1

Views: 62

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627292

Use nested optional groups. Note you may also shortne the boundary patterns by replacing (?:^|(?<= )) and (?:(?= )|$) alternations with (?<!\S) and (?!\S) lookarounds.

The pattern will look like

(?<!\S)(serv(?:i(?:ce?)?)?|gene(?:r(?:ic?)?)?|comp(?:u(?:t(?:er?)?)?)?|mast(?:er?)?)(?!\S)

See the regex demo

Details

  • (?<!\S) - no non-whitespace immediately to the left of the current location is allowed
  • ( - alternation group start:
    • serv(?:i(?:ce?)?)? - serv, servi, servic, or service
    • | - or
    • gene(?:r(?:ic?)?)? - gene, gener, generi or generic
    • | - or
    • comp(?:u(?:t(?:er?)?)?)? - comp, compu, comput, compute or computer
    • | - or
    • mast(?:er?)? - mast, maste or master
  • ) - end of the alternation group
  • (?!\S) - no non-whitespace immediately to the right of the current location is allowed.

Upvotes: 1

Related Questions