简体   繁体   中英

Need help to match specific characters with a Java regex

I need to match characters that do not belong to the following character set :

abcdefghijklmnopqrstu vwxyz ABCDEFGHIJKLMNOPQRSTU VWXYZ 0 1 2 3 4 5 6 7 8 9 / - ? : ( ) . , ' + space

To do that, I'm using this regex :

String regex = "[^\\da-zA-Z/\\-\\?:\\(\\)\\.\\,'\\+ ]+";

Unfortunatly, that does not work.

I tried this too (negation):

String regex = "(?![\\da-zA-Z/\\-\\?:\\(\\)\\.\\,'\\+ ]+)";

But it's not ok.

Anyone can help ?

I don't think you can use a predefined character class like \\d inside another character class. Also, most of the characters you're escaping aren't special within a character class (although the escaping should be harmless). So:

String regex = "[^0-9a-zA-Z/\\-?:().,'+ ]+";

Side note: In your question, you said you wanted to replace ' (a fancy curly apostrophe), but in your regex you have just a normal apostrophe ' . So change that if needed.

Here's a test:

public class RegTest {
    public static final void main(String[] args) {
        String regex, test, result;

        // First, test without the negation and make sure it *does* replace the target chars
        regex = "[0-9a-zA-Z/\\-?:().,'+ ]+";
        test = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-?:().,'+";
        result = test.replaceAll(regex, "%");
        System.out.println(result);
        // Prints %

        // Now, test *with* the negation and make sure it matches other characters (I put
        // a few at the beginning) but not those
        regex = "[^0-9a-zA-Z/\\-?:().,'+ ]+";
        test = "[@!\"~abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-?:().,'+";
        result = test.replaceAll(regex, "%");
        System.out.println(result);
        // Prints %abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/-?:().,'+
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM