I’m using php’s preg_replace function, and I have the following regex:
(?:[^>(),]+)
to match any characters but >(),. The problem is that I want to make sure that there is at least one letter in it (\w) and the match is not empty, how can I do that?
Is there a way to say what i DO WANT to match in the [^>(),]+ part?
You can add a lookahead assertion:
This makes sure that there will be at least one letter (
\p{L};\walso matches digits and underscores) somewhere in the string.You don’t really need the
(?:...)non-capturing parentheses, though:works just as well. Also, to ensure that we always match the entire string, it might be a good idea to surround the regex with anchors:
EDIT:
For the added requirement of not including surrounding whitespace in the match, things get a little more complicated. Try
In PHP, for example to replace all those strings we found with
REPLACEMENT, leaving leading and trailing whitespace alone, this could look like this: