我需要验证模式是否有字母“B”,并且在它之后最多六个符号(字母和数字)。例如:我们有abcdB1234B123456
. 找到的答案应该是:B1234
和B123456
。
我做了这个模式:
[^B]{1,6}
但它不精确..
What about this pattern:
public static void main(String[] args) {
final Pattern pattern = Pattern.compile("B[aAc-zC-Z0-9]{0,6}");
final String string = " abcdB1234B123456";
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println(matcher.group());
}
}
Output:
B1234
B123456
Try this code :
String data = "abcdB1234B123456";
Pattern pattern = Pattern.compile("B[aAc-zC-Z\\d]{0,6}");
Matcher matcher = pattern.matcher(data);
while (matcher.find()) {
// Indicates match is found. Do further processing
System.out.println(matcher.group());
}