Java detects special characters in a string

I am using regex

r="[^A-Za-z0-9]+"; 

to determine whether a string contains one or more characters except letters and numbers;

Then I tried the following:

 Pattern.compile(r).matcher(p).find(); 

I tested:

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

In most cases, it works except backsplash \ and caret ^.

eg.

 String p = "abcAsd10^" (return false) String p = "abcAsd10\\" (return false) 

What am I missing?

+4
source share
7 answers

The following code prints β€œFound: true” when compiling and running:

 class T { public static void main (String [] args) { String thePattern = "[^A-Za-z0-9]+"; String theInput = "abskKel35^"; boolean isFound = Pattern.compile(thePattern).matcher(theInput).find(); System.out.println("Found: " + isFound); } } 

Not sure why you will see another result ...

+2
source

Must not be:

 r="[^A-Za-z0-9]+"; 

In your question you write a_z (underscore)

+1
source

You can also only change:

 [\w&&^_]+ 

Where:

  • \w Underline character: [a-zA-Z_0-9]
  • \w Character without a word: [^\w]

More in class Pattern

+1
source

When I run this code on my machine, it outputs true.

  String r="[^A-Za-z0-9]+"; String p = "abcAsd10\\" ; Matcher m = Pattern.compile(r).matcher(p); System.out.println(m.find()); 

True

+1
source

Try to match your input.

 Pattern.quote(p) 
0
source

Sorry, I had

 r="[^A-za-z0-9]+"; (with little "z", ie Az). 

This results in a return of false. But why does it work with other special characters besides backsplash \ and caret ^?

0
source

Just do:

 p.matches(".*\\W.*"); //return true if contains one or more special character 
0
source

Source: https://habr.com/ru/post/1416215/


All Articles