我应该为以下模板使用什么样的正则表达式?

时间:2016-10-06 05:52:23

标签: java regex matcher

我正在编写一个Java程序来计算一个人的平均工资,并在模板中打印每月扣除额。模板是这样的:

==============BILL==============
|  NAME: xXxX     BRANCH : xxx |
|                              |
|    Month 1 : xxx.xxx         |
|    Month 2 : xxxx.xx         |
|     <other Months>           |
|    Month 12 : xxx.xx         |
|                              |
|     TOTAL : ____________     |
================================

我使用以下模式尝试捕获元素:

//template is stored in string.
String[] lines = msg.split("\n");
Pattern p = Pattern.compile("[xX\\._]+");
for(String line : lines){
    Matcher m = p.matcher(line);
    if(m.find()){
        System.out.println(m.group());
    }
    else{
        System.out.println("no match found...");
    }
}

我得到的输出是这样的:

xXxX
xxx.xxx
xxxx.xx
xxx.xx
____________

但是,我无法匹配BRANCH的'xxx'。如何提取该模式?

1 个答案:

答案 0 :(得分:0)

更改

if(m.find()){
    System.out.println(m.group());
}

while(m.find()){
        System.out.println(m.group());
}

NAMEBRANCH位于同一行。

Matcher#find()会在字符串中找到第一个匹配项,而不是所有匹配项。要获得所有匹配,您必须多次拨打find()

相关问题