开发者

Is there a not (!) operator in regexp?

I need to remove all characters from the given string except for开发者_StackOverflow社区 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**".


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**
    }
}


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.


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.


In a character class the ^ is not. So

[^1a\*] would match all characters except those.


You want to match against all characters except: [asdf123*], use ^


There's no "not" operator in Java regular expressions like there is in Perl.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜