[英]What kind of regex should I use for the following template?
我正在編寫一個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'。 如何提取該模式?
更改
if(m.find()){
System.out.println(m.group());
}
至
while(m.find()){
System.out.println(m.group());
}
NAME
和BRANCH
在同一條線上。
Matcher#find()
將在字符串中找到第一個匹配項,而不是所有匹配項。 要獲得所有匹配,您必須多次調用find()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.