Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to negate specific word in regex? [duplicate]

Tags:

regex

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"?

like image 276
Bostone Avatar asked Aug 06 '09 17:08

Bostone


People also ask

How do you write a negation in regex?

Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.

How do I remove a specific character from a regular expression?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

What does \b do in regular expression?

Simply put: \b allows you to perform a “whole words only” search using a regular expression in the form of \bword\b. A “word character” is a character that can be used to form words. All characters that are not “word characters” are “non-word characters”.


1 Answers

A great way to do this is to use negative lookahead:

^(?!.*bar).*$ 

The negative lookahead construct is the pair of parentheses, with the opening parenthesis followed by a question mark and an exclamation point. Inside the lookahead [is any regex pattern].

like image 164
Chris Van Opstal Avatar answered Sep 28 '22 22:09

Chris Van Opstal