Reputation: 623
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
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
|
- orgene(?:r(?:ic?)?)?
- gene
, gener
, generi
or generic
|
- orcomp(?:u(?:t(?:er?)?)?)?
- comp
, compu
, comput
, compute
or computer
|
- ormast(?: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