myanmar myanmar - 5 months ago 11
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

You may want to use for this

^ABC[0-9]{5}$

  • ^ : 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


Regex101


Example

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

EDIT

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.

.*ABC[0-9]{5}.*


EDIT 2

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);
    m.find();
    result = m.group();
}