Character classes in regular expressions do not provide alternation, meaning the use of |
will be treated as a literal character and the ^
must be placed at the start of the class to have its intended effect (otherwise it will be taken literally).
To achieve this, you can utilize the following pattern:
[^\w+-]+
(Additionally, if the hyphen -
is not positioned last within the class, it should be escaped as \-
to avoid misinterpretation - so caution must be exercised when modifying the exception list).
An alternative approach would involve using a negative lookahead like so:
(?![+-])\W
Note: Avoid adding a *
or +
after \W
, as the lookahead only applies to the immediately succeeding character (and utilizing the global flag g
ensures the replacement continues until completion).
Furthermore, it is important to remember that \w
and
\W</code both consider underscores <code>_
as word characters. To address this, you can replace it by using
(?![+-])[\W_]
(or implement explicit ranges in the initial expressions).