Home > OS >  Regex Match - How to match a string that does not contain a specific char
Regex Match - How to match a string that does not contain a specific char

Time:01-29

I'm looking for a regex expression that will match a word (or anything splitted by space) that does not contain a specific character.

For example: foo anot%her bar idk%what @IJ#N, I need to match a word does noot contain % character, the result is foo, bar and @IJ#N.

I tried something like this, but it doesn't work:

CodePudding user response:

Instead of using a word boundary and an anchor at the end, you can write the pattern using lookarounds if those are supported and then match any non whitespace character except for the % using a negated character class:

(?<!\S)[^\s%] (?!\S)

See a regex101 demo

CodePudding user response:

Since your words contain symbols, you can't use \w and \b here. \S Matches anything other than a space, tab or newline. Negative Lookahead (?!\S*%\S*) ensures that % is not contained in the string. Finally, add the anchors ^ and $. The pattern is ^(?!\S*%\S*)\S $, see https://regex101.com/r/DjZFZj/1. If your string is a long string separated by white spaces, just change the boundary. You can change ^ to (?<=^|\s) and delete the $, the pattern is (?<=^|\s)(?!\S*%\S*)\S , see https://regex101.com/r/0rBhF2/1.

  • Related