我需要查找字符串是否以“abcd”开头,后跟 1-5 位数字,然后是逗号,然后以 0-3 位数字结尾。
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());
}
}
输出 :
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.
使用它,我可以确保以部分结尾。我想我只能停止像这样的字符串了"pqrsabcd12345,5"
如果我错过了什么,请告诉我。