我正在尝试解析一些文本,但是由于某种奇怪的原因,Java regex无法工作。例如,我尝试过:
Pattern p = Pattern.compile("[A-Z][0-9]*,[0-9]*");
Matcher m = p.matcher("H3,4");当我尝试获取数字m.group(1)和m.group(2)时,它只是给出了No match found异常。关于Java regex的工作原理,我是不是漏掉了什么?
发布于 2011-11-18 11:20:31
是。
matches()或find()。示例:
Pattern p = Pattern.compile("[A-Z](\\d*),(\\d*)");
matcher m = p.matcher("H3,4");
if (m.matches()) {
// use m.group(1), m.group(2) here
}发布于 2011-11-18 11:29:18
您还需要使用括号来指定属于每个组的内容。我将前导部分改为任何不是数字的部分,0或更多次。每组中的数字是1位或更多。所以,不是*而是+。
Pattern p = Pattern.compile("[^0-9]*([0-9]+),([0-9]+)");
Matcher m = p.matcher("H3,4");
if (m.matches())
{
String g1 = m.group(1);
String g2 = m.group(2);
}https://stackoverflow.com/questions/8177322
复制相似问题