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.
-
In the future make sure you tag your questions with the appropriate language. – Biffen Jul 03 '16 at 13:01
-
I forgot it. Tack so micke :) – myanmar Jul 03 '16 at 13:05
-
1This sounds like a regex solution. – Gherbi Hicham Jul 03 '16 at 13:13
-
Yes, you are right. But how to write a regex for this. – myanmar Jul 03 '16 at 13:14
-
Possible duplicate of [What is the fastest way to search for substring in Java?](http://stackoverflow.com/questions/24602422/what-is-the-fastest-way-to-search-for-substring-in-java) – Jul 03 '16 at 13:22
6 Answers
You may want to use regex for this
^ABC[0-9]{5}$
^
: Beginning of the stringABC
: 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();
}

- 21,337
- 9
- 51
- 89
-
Yes, but your solution doesn't work for **String one = "textABC72961text";** and I need to return this string if it exists. – myanmar Jul 03 '16 at 13:27
-
@myanmar If it should work for this, you need to excluse `^` and `$` – Yassin Hajaj Jul 03 '16 at 13:28
-
1@myanmar Next time be sure about your specifiations and post them. It'll make it easy for everyone to find the correct answer; – Yassin Hajaj Jul 03 '16 at 13:29
-
You are absolutely right. But it doesn't work again. I got false as a result. – myanmar Jul 03 '16 at 13:34
-
@myanmar [`[\\w]+ABC[0-9]{5}[\\w]+`](https://regex101.com/r/cB1jP8/1) You want to match the entire string I suppose? This will do. – Yassin Hajaj Jul 03 '16 at 13:36
-
Yes, it works now. Can I somehow return this string from a given text. I have String one = "textABC72961text" and I need to return "ABC72961" because it matches the pattern – myanmar Jul 03 '16 at 13:40
-
1@YassinHajaj Using `\\w` means that it only finds the substring if all other characters are word-characters but special character should be allowed too, and using `+` means there has to be such characters. Replace with `.*`, as in `matches(".*ABC[0-9]{5}.*")`. – Andreas Jul 03 '16 at 13:49
-
Exception in thread "main" java.lang.IllegalStateException: No match found at java.util.regex.Matcher.group(Unknown Source) at test.Test.main(Test.java:15) – myanmar Jul 03 '16 at 13:59
-
-
You can use the String indexOf command like this:
int result = someString.indexOf("ABC72961")
result will be -1 if there are no matches.
If there is a match, the result will be the index where the match starts.
-
Yes, but the string contains always wit "ABC" but the five digit number can be different. And I have to say if there is a string which starts with ABC following by 5 digits. – myanmar Jul 03 '16 at 13:11
str.contains("ABC72961");
Returns true if str
contains the string. False if not.

- 1,986
- 4
- 23
- 47
-
Yes, but the string contains always wit "ABC" but the five digit number can be different. And I have to say if there is a string which starts with ABC following by 5 digits. – myanmar Jul 03 '16 at 13:11
-
-
I have to return this String from a given text or find such string in a given text. – myanmar Jul 03 '16 at 13:16
-
Ok, now you're just changing the desired outcome every time someone makes a suggestion. – Alec Jul 03 '16 at 13:19
-
No, it is not my attention to do this. Someone can correct my questions. For example, I have String one = "textABC72961text" and I need to return "ABC72961" because it matches the pattern. – myanmar Jul 03 '16 at 13:36
I think what you want to use is java.util.regex.Pattern
.
Pattern p = Pattern.compile("ABC(\d*)");
Matcher m = p.matcher("ABC72961");
boolean b = m.matches();
or if it shall be exactly 5 digits after "ABC", you can use the regex ABC(\d{5})
https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)
Another solution would be:
String stringToTest = "ABC72961"
boolean b = stringToTest.contains("ABC");

- 320
- 4
- 18
public String getString() {
String str = extractString();
return str;
}
public boolean exists() {
return !getString().trim().equals("") ? false : true;
}
private List<Integer> getPositionsOfABC() {
List<Integer> positions = new ArrayList<>();
int index = text.indexOf("ABC");
while (index > 0) {
positions.add(index);
index = text.indexOf("ABC", index + 1);
}
return positions;
}
private static boolean isInteger(String str) {
boolean isValidInteger = false;
try {
Integer.parseInteger(str);
isValidInteger = true;
} catch (NumberFormatException ex) {
return isValidInteger;
}
return isValidInteger;
}
private String extractString() {
List<Integer> positions = getPositionsOfABC();
for (Integer position : positions) {
int index = position.intValue();
String substring = text.substring(index, index + LENGTH_OF_DIGITS);
String lastDigits = substring.substring(3, substring.length());
if (isInteger(lastDigits)) {
return substring;
}
}
return "";
}

- 81
- 1
- 2
- 11
Here's a simple code that checks whether a substring exists in a string without using library functions, regex or other complex data structures.
class SSC {
public static void main(String[] args) {
String main_str <-- MAIN STRING
String sub_str <-- SUBSTRING
String w; int flag=0;
for(int i=0;i<=main_str.length()-sub_str.length();i++){
w="";
for(int j=0;j<sub_str.length();j++){
w+=main_str.charAt(i+j);
}
if(w.equals(sub_str))
flag++;
}
if(flag>0)
System.out.print("exists "+flag+" times");
else
System.out.print("doesn't exist");
}
}
Hope this helps.