Reputation: 119
I need to find a license plate number in a text matching a pattern like this below ("L" stands for a letter,"D" stands for a number):
LLLDDD,LLLDDDD,LLDDDD,DDDDLL
there can be spaces between them like LLL DDD
I have this method that works fine if the text is just the license plate number like for example "SS1234"
public static boolean plateNumberExist(String target) {
return Pattern.compile("^([A-Za-z]{3} ?[0-9]{3})?([A-Za-z]{3} ?[0-9]{4})?([A-Za-z]{2} ?[0-9]{4})?([0-9]{4} ?[A-Za-z]{2})?$").matcher(target).matches();
}
But if i add another text with the license plate number like the code below then its always false
if(plateNumberExist("Republic SS1234")){
showToast("Plate Number Found");
}else{
showToast("No Plate Number");
}
So the actual code that i am using to get the license plate number is the code below but it also doesn't work.
String inputString = "Republic SS1234";
Pattern pattern = Pattern.compile("^([A-Za-z]{3} ?[0-9]{3})?([A-Za-z]{3} ?[0-9]{4})?([A-Za-z]{2} ?[0-9]{4})?([0-9]{4} ?[A-Za-z]{2})?$");
Matcher matcher = pattern.matcher(inputString);
if (matcher.find()) {
String platenumber = inputString.substring(matcher.start(), matcher.end());
showToast(platenumber);
} else {
showToast("No Plate Number Found");
}
The problem is with the regex but i just don't understand why it works if its only a license plate number but if i have other text with the license plate number it doesn't work
Upvotes: 2
Views: 334
Reputation: 85371
The ^
and $
regex symbols denote the beginning and end of the input, respectively.
Replace those with \\b
(beginning/end of a word), and it should work.
== Edit ==
Note that your regex itself can be simplified and you should use a loop if you want to collect all matches. Have a look:
String inputString = "Republic SS1234 and ABC 1234";
Pattern pattern = Pattern.compile(
"(?i)\\b([A-Z]{3} ?[0-9]{3,4}|[A-Z]{2} ?[0-9]{4}|[0-9]{4} ?[A-Z]{2})\\b");
Matcher matcher = pattern.matcher(inputString);
while (matcher.find()) {
String platenumber = matcher.group(1);
. . .
}
(?i)
means ignore-case, {3,4}
means "from 3 to 4" and |
means "or"
Upvotes: 4