如何找到“B”+最多6个标志

时间:2013-03-24 15:20:03

标签: java regex

我需要验证,如果模式有字母“B”,后面有六个符号(字母和数字)。例如:我们有abcdB1234B123456。找到的答案应为:B1234B123456

我做了这个模式:

[^B]{1,6}

但不准确......

2 个答案:

答案 0 :(得分:5)

这种模式怎么样:

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());
    }
}

输出:

B1234
B123456

答案 1 :(得分:2)

试试这段代码:

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());
}