Example: search for the pattern man
but only as the beginning of a word (i.e. not preceded directly by letters).
This pattern would be found in the strings man
, spider-man
, manpower
, iron_man
. But not in woman
or human
.
Example: search for the pattern man
but only as the beginning of a word (i.e. not preceded directly by letters).
This pattern would be found in the strings man
, spider-man
, manpower
, iron_man
. But not in woman
or human
.
I have assumed that if the word "man"
is preceded by a hyphen or underscore, to achieve a match the hyphen or underscore must be preceded by a letter (e.g., "-man"
would not be matched).
The \K
escape sequence resets the beginning of the match to the current position in the token list. If supported by the regex engine, the following regular expression (with the case-indifferent flag set) could be used.
(?:^| |[a-z][-_])\Kman
The selected answer to this SO question provides a list of regex engines that support \K
. That list was last updated in August 2019.
The regex engine performs the following operations.
(?: # begin non-capture group
^ # match beginning of line
| # or
# match a space
| # or
[a-z] # match a letter
[-_] # match '-' or '_'
) # end non-capture group
\K # discard everything matched so far
man # match 'man'
Alternatively, a capture group could be used.
(?:^| |[a-z][-_])(man)