Matches in a string in Java

104 views Asked by At

I have this code:

String string = "40' & 40' HC";
if(string.matches("&"))
   System.out.println("Found");

But the condition won't be true. why? Help is appreciated. Thanks

3

There are 3 answers

0
Elliott Frisch On BEST ANSWER

String.matches(String) is for a regular expression. I suggest you add an else (and {}) and I believe you wanted contains and something like

if (string.contains("&")) {
    System.out.println("Found");
} else {
    System.out.println("Not found");
}
0
Ashish Yete On
String string = "40' & 40' HC";
if(string.contains("&"))
 System.out.println("Found");

replace .matches with .contains, i believe you are trying to check for a character in the string.

0
Arjit On

It's misnamed .matches() method in JAVA. It tries and matches ALL the input.

String.matches returns whether the whole string matches the regex, not just any substring.

Use Pattern

String string = "40' & 40' HC";
Pattern p = Pattern.compile("&");
Matcher m = p.matcher(string);
if (m.find())
  System.out.println("Found");