Java正则表达式Matcher.end()没有返回所需的索引

时间:2015-03-11 03:11:34

标签: java regex

我是Java中的regex的新手,想要编写一个匹配特定模式的正则表达式,并在匹配后立即获得下一个索引。我写了以下代码:

temp = "contains(text(),\"something\")]"
String pattern = "^contains\\(text\\(\\),\"(.*)\"\\)";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(temp);
if(m.find())
{   
    value = m.group(0);
    type = CONTAINS;
    pointer = m.end();
    //System.out.println(m.group(1));
}

此后,指针超出范围。请注意,我提供的正则表达式模式在)结束,因此我希望指针的索引为],但事实并非如此。我在这里缺少什么?

1 个答案:

答案 0 :(得分:1)

您可能会错误地计算您期望]的位置。请记住,引号的转义\不计算,因为它们在构建字符串时消失。

这里证明它可以找到]

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Regex {

    public static void main(String[] args) throws Exception
    {

        String temp = "contains(text(),\"something\")]";
        String pattern = "^contains\\(text\\(\\),\"(.*)\"\\)";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(temp);
        if(m.find())
        {   
            String value = m.group(0);
            System.out.println(value+" <-- value"); //TODO remove debugging code
//            type = CONTAINS;  //<- no idea what this was for
            int pointer = m.end();
            System.out.println(pointer+" <-- pointer"); //TODO remove debugging code

            System.out.println(m.group(1)+" <-- m.group(1)");

            System.out.println(temp.substring(pointer, pointer+1)
                +" <-- temp.substring(pointer, pointer+1)"); //TODO remove debugging code
        }
    }
}

打印

contains(text(), "something") <-- value
28 <-- pointer
something <-- m.group(1)
] <-- temp.substring(pointer, pointer+1)