2

i want to blacklist only some special characters(<,>,%,$,^) from a string and allow everything else. i have been trying some regular expressions but they are not working.for e.g. [^%<>] but its not working.

String s = "script";
    if(s.matches("[^%<>\\$]")){
        System.out.println("valid");
    }else{
        System.out.println("invalid");
    }

please suggest some solution

anonymous
  • 244
  • 2
  • 4
  • 23

2 Answers2

4

i want to blacklist only some special characters(<,>,%,$,^) from a string and allow everything else.

You can use this regex:

^[^%<>^$]+$

PS: For using in String#matches you don't even line start/end anchors ^ and $ and can use code like this:

String s = "script";
if( s.matches("[^%<>^$]+") ) {
    System.out.println("valid");
} else {
    System.out.println("invalid");
}
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • @skiwi: Inside character class `[ and `] they need not be escaped. – anubhava Dec 07 '13 at 17:48
  • it should be valid for String s = " – anonymous Dec 07 '13 at 17:51
  • See working demo: http://ideone.com/IKuV3R and no ` – anubhava Dec 07 '13 at 17:52
  • 2
    ` – m0skit0 Dec 07 '13 at 17:55
  • but in both case it prints invalid... for e.g: "script" should be valid and " – anonymous Dec 07 '13 at 17:56
  • @anonymous: I am really surprized to read your comment. Did you even see the demo link I provided: above (http://ideone.com/IKuV3R) for `script` it prints `valid` and for ` – anubhava Dec 07 '13 at 17:58
  • @anubhava i m looking at it... n ur code is working.. i am surprised that it wasnt working for me... thankyou... and sorry.... – anonymous Dec 07 '13 at 18:01
0

Another example which black lists all these characters: [ " : * ? < > ^ $ \ | / ]

/^[^":*?<>^$\\|\\/]+$/
Rufat Gulabli
  • 634
  • 6
  • 10