I know that I can negate group of chars as in [^bar]
but I need a regular expression where negation applies to the specific word - so in my example how do I negate an actual "bar"
and not "any chars in bar"
?
相关问题
- Improve converting string to readable urls
- Regex to match charset
- Regex subsequence matching
- Accommodate two types of quotes in a regex
- Set together letters and numbers that are ordinal
相关文章
- Optimization techniques for backtracking regex imp
- Regex to check for new line
- Allow only 2 decimal points entry to a textbox usi
- Comparing speed of non-matching regexp
- Regular expression to get URL in string swift with
- 请问如何删除之前和之后的非字母中文单字
- Lazy (ungreedy) matching multiple groups using reg
- when [:punct:] is too much [duplicate]
You could either use a negative look-ahead or look-behind:
Or use just basics:
These all match anything that does not contain
bar
.I hope to complement the answer
As the Chris specified Regex Tutorial is a best resource for learning regex.
However, it really consumed time to read through.
I make a cheatsheet for the mnemonic convenience.
[]
,()
,{}
leading each class which is easy to recall.Just thought of something else that could be done. It's very different from my first answer, as it doesn't use regular expressions, so I decided to make a second answer post.
Use your language of choice's
split()
method equivalent on the string with the word to negate as the argument for what to split on. An example using Python:The nice thing about doing it this way, in Python at least (I don't remember if the functionality would be the same in, say, Visual Basic or Java), is that it lets you know indirectly when "bar" was repeated in the string due to the fact that the empty strings between "bar"s are included in the list of results (though the empty string at the beginning is due to there being a "bar" at the beginning of the string). If you don't want that, you can simply remove the empty strings from the list.
A great way to do this is to use negative lookahead:
The accepted answer is nice but is really a work-around for the lack of a simple sub-expression negation operator in regexes. This is why
grep --invert-match
exits. So in *nixes, you can accomplish the desired result using pipes and a second regex.Still a workaround, but maybe easier to remember.
Unless performance is of utmost concern, it's often easier just to run your results through a second pass, skipping those that match the words you want to negate.
Regular expressions usually mean you're doing scripting or some sort of low-performance task anyway, so find a solution that is easy to read, easy to understand and easy to maintain.