I need to find if a String starts with "abcd" followed by 1-5 digits, then a comma, then ends with 0-3 digits.
Pattern pattern = Pattern.compile("abcd[0-9]{1,5},[0-9]{0,3}$");
String[] data = { "pqrsabcd12345,5", "abcd1234,5", "abcd1234542155,",
"abcdSD12345,555", "abcd123,555", "abcd12,5555",
"abcd,5555ffdfd", "abcd2,5555ffdfd", "abcd2,5" };
for (CharSequence input : data) {
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.format("\nI found the text %s :"
+ " \"%s\" starting at "
+ "index %d and ending at index %d.%n", input,
matcher.group(), matcher.start(), matcher.end());
}
}
The output :
I found the text pqrsabcd12345,5 : "abcd12345,5" starting at index 4 and ending at index 15.
I found the text abcd1234,5 : "abcd1234,5" starting at index 0 and ending at index 10.
I found the text abcd123,555 : "abcd123,555" starting at index 0 and ending at index 11.
I found the text abcd2,5 : "abcd2,5" starting at index 0 and ending at index 7.
Using this, I could ensure the ends with part. I think I am left with stopping Strings like "pqrsabcd12345,5"
Please let me know if I have missed something.
本文介绍了一种使用正则表达式来验证特定格式字符串的方法。通过Java的Pattern和Matcher类实现对字符串进行模式匹配,确保字符串符合预设的格式:以abcd开头,后面跟着1到5位数字,接着是逗号,最后以0到3位数字结尾。
5098

被折叠的 条评论
为什么被折叠?



