【发布时间】:2013-06-27 05:07:17
【问题描述】:
我有以下模式:
Pattern TAG = Pattern.compile("(<[\\w]+]>)|(</[\\w]+]>)");
请注意 |在模式中。
我有一个方法可以用这个模式做一些处理
private String format(String s){
Matcher m = TAG.matcher(s);
StringBuffer sb = new StringBuffer();
while(m.find()){
//This is where I need to find out what part
//of | (or) matched in the pattern
// to perform additional processing
}
return sb.toString();
}
我想根据 OR 中匹配的部分执行不同的功能 正则表达式。我知道我可以将模式分解为 2 个不同的模式并在每个模式上进行匹配,但这不是我正在寻找的解决方案,因为我的实际正则表达式要复杂得多,如果我能做到的话,我想要完成的功能效果最好它在一个循环和正则表达式中。所以我的问题是:
在 java 中有没有办法找出 OR 的哪一部分在正则表达式中匹配?
编辑
我也知道 m.group() 功能。它不适用于我的情况。下面的例子
打印出<TAG> 和</TAG> 所以对于循环的第一次迭代它匹配<[\\w]+>
第二次迭代匹配</[\\w]+>。但是我需要知道每次迭代中匹配的部分。
static Pattern u = Pattern.compile("<[\\w]+>|</[\\w]+>");
public static void main(String[] args) {
String xml = "<TAG>044453</TAG>";
Matcher m = u.matcher(xml);
while (m.find()) {
System.out.println(m.group(0));
}
}
【问题讨论】:
-
请注意您对
group(0)的使用与group(1)或任何其他索引不同 - 第0 组是特殊的,因为它返回整个匹配项。添加括号可以让您根据需要访问匹配的较小部分。 -
我在你的第一个模式中更正了
/,因为你知道(<[\\w]+]>)|(</[\\w]+]>)至少我没有误会你的意思:)
标签: java regex pattern-matching