Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a not (!) operator in regexp?

Tags:

java

regex

I need to remove all characters from the given string except for several which should left. How to do that with regexp?

Simple test: characters[1, a, *] shouldn't be removed, all other should from string "asdf123**".

like image 514
Roman Avatar asked Oct 05 '10 17:10

Roman


People also ask

Is there a not operator in regex?

No, there's no direct not operator.

Is exclamation mark a special character in regex?

occurs as the first character in a regular expression, all magic characters are treated as special characters. An exclamation mark is treated as a regular character if it occurs anywhere but at the very start of the regular expression.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).

What is not in regular expression?

NOT REGEXP in MySQL is a negation of the REGEXP operator used for pattern matching. It compares the given pattern in the input string and returns the result, which does not match the patterns. If this operator finds a match, the result is 0.


3 Answers

There is: ^ in a set.

You should be able to do something like:

text = text.replaceAll("[^1a*]", "");

Full sample:

public class Test
{
    public static void main(String[] args)
    {
        String input = "asdf123**";
        String output = input.replaceAll("[^1a*]", "");
        System.out.println(output); // Prints a1**
    }
}
like image 172
Jon Skeet Avatar answered Nov 15 '22 18:11

Jon Skeet


When used inside [ and ] the ^ (caret) is the not operator.

It is used like this:

"[^abc]"

That will match any character except for a b or c.

like image 26
jjnguy Avatar answered Nov 15 '22 19:11

jjnguy


There's a negated character class, which might work for this instance. You define one by putting ^ at the beginning of the class, such as:

[^1a\*]

for your specific case.

like image 44
eldarerathis Avatar answered Nov 15 '22 18:11

eldarerathis