myanmar myanmar - 1 year ago 69
Java Question

does text contains substring

How to check if some String contains a specific String like "ABC72961". So we search for String which starts with "ABC" following by 5 digits. I've implemented a algorithm but I want it with "matches" or somehow else and then check the speed of these two solutions.

Answer Source

You may want to use for this


  • ^ : Beginning of the string
  • ABC : Matches ABC literally (case-sensitive)
  • [0-9]{5} : Matches 5x numbers from 0 to 9
  • $ : End of the string

And use String#matches to test it



String regex = "^ABC[0-9]{5}$";
String one = "ABC72961";
String two = "ABC2345";
String three = "AB12345";
String four = "ABABABAB";

System.out.println(one.matches(regex));      // true
System.out.println(two.matches(regex));      // false
System.out.println(three.matches(regex));    // false
System.out.println(four.matches(regex));     // false


Seeing your comment, you want it to work for String one = "textABC72961text" also. For that to be possible, you should just erase ^ and $ that limit the String.



Here is if you want to extract it

if (s.matches(".*ABC[0-9]{5}.*")) {
    Matcher m = Pattern.compile("ABC[0-9]{5}").matcher(s);
    result =;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download