-1

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

rosiejaneenomar
  • 882
  • 1
  • 10
  • 17

3 Answers3

3

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");
}
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1
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.

Ashish Yete
  • 51
  • 1
  • 7
0

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");
Arjit
  • 3,290
  • 1
  • 17
  • 18