-2

在这里,我使用正则表达式来捕获前 15 个字符进行匹配,并且在使用子字符串时我必须使用 (0,matcher.start()) ,其中我应该只得到 15,请帮助我。

   String test = "hello world this is example";
        Pattern p = Pattern.compile(".{15}");

    //can't change the code below
    //can only make changes to pattern 


        Matcher m=p.matches(test);
        matcher.find(){
            String string = test.substring(0, m.start());
        }

    //here it is escaping the first 15 characters but I need them
    //the m.start() here is giving 0 but it should give 15
4

2 回答 2

0

您应该使用 Matcher.end() 而不是 Matcher.start()。

String test = "hello world this is example";
            Pattern p = Pattern.compile(".{15}");
            Matcher m=p.matcher(test);
            if(m.find()){
                String string = test.substring(0, m.end());
                System.out.println(string);
            }       

来自 API:

  1. Matcher.start() ---> 返回上一个匹配的开始索引。
  2. Matcher.end() ---> 返回最后一个匹配字符后的偏移量。
于 2013-01-15T15:14:34.827 回答
0

如果可能的话,我同意@jlordo 的评论:使用String string = test.substring(0, 15);

如果您被迫通过标记为不可更改的底部代码片段,则有一种解决方法。(这取决于...如果您遇到无法更改的代码片段甚至无法编译...您将度过一段糟糕的时光)

如果你真的需要一个总是返回 15 的正则表达式,m.start()你可以使用正则表达式lookbehind concept

        String test = "hello world this is example";
        Pattern p = Pattern.compile("(?<=.{15}).");

        Matcher m=p.matcher(test);
        m.find();
        System.out.println(m.start());

假设test输入字符串至少有 16 个字符长,这将始终返回 15 m.start()。正则表达式应该被读作“任何字符(最后一个 .),前面有((?<=)lookbehind 运算符)正好 15 个字符(.{15})”。

(?<=foo)是一个后向运算符,指定后面的任何正则表达式都必须以“foo”开头。例如,正则表达式:(?<=foo)bar
将匹配中的栏:foobar
但不匹配中的栏:wunderbar

于 2013-01-15T16:00:17.707 回答