简体   繁体   中英

Regex to Match: !$%^&*()_+|~-=`{}[]:";'<>?,./

I know this a duplicate of a question with almost the identical name, however, I can't get it to work in Android what so ever!

I am trying this: Regex to Match Symbols:

public Pattern bsymbols = Pattern.compile("[-!$%^&*()_+|~=`{}\\[\\]:\\";'<>?,.\/]");

However, this isn't working. Does anyone know the correct method of applying this pattern?

PS Complete noob at Regex. :D

From here originally - Regex to Match Symbols: !$%^&*()_+|~-=`{}[]:";'<>?,./

Error Message: Syntax error on token(s), misplaced construct(s)

UPDATE: Added extra backslashes...fixed a lot of em, now gets error from ; onwards. Using Eclipse.

I think your problem is the "

public Pattern bsymbols = Pattern.compile("[-!$%^&*()_+|~=`{}\[\]:";'<>?,.\/]");
                                                                  ^

it is ending your string, so you should escape it. Also you need to remove the backslash before the slash, it is no special character.

public Pattern bsymbols = Pattern.compile("[-!$%^&*()_+|~=`{}\\[\\]:\";'<>?,./]");

OK, once more, you wanted to match the backslash, not to escape the slash, then we end up here:

public Pattern bsymbols = Pattern.compile("[-!$%^&*()_+|~=`{}\\[\\]:\";'<>?,.\\\\/]");

now it is the same answer, than jdb's, so +1 to him for being quicker.

那个怎么样?

Pattern.compile("[-!$%^&*()_+|~=`{}\\[\\]:\";'<>?,.\\\\/]");

In a character class, only [ and ] have special meaning, so you need to escape them. Plus in Java, you need to escape with an extra backslash. That's the problem specifically with Java. So, you need to use \\\\[ and \\\\] . And yes, you need to escape " with single backslash, in a string literal.

Apart from that, a hyphen when used somewhere in the middle, has also a special meaning. If you want to match a hyphen , you need to use it at the ends.

Rest of the characters, don't need to be escaped. They are just ordinary characters.

So, your pattern should be like this: -

Pattern bsymbols = Pattern.compile("[-!$%^&*()_+|~=`{}\\[\\]:\";'<>?,./]");

And if you want to match backslash (\\) also, then use this: -

Pattern bsymbols = Pattern.compile("[-!$%^&*()_+|~=`{}\\[\\]:\";'<>?,.\\\\/]");

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