1

我的示例代码:

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

public class Test {

    /**
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        String str[] = {"A","B","C"};
        String s = "TEST FOR A STRING CONSTANT B. END.";
        int retIndex = -1;

        for (int i = 0, len = str.length; i < len; i++){ 
            //length-1 is because, we should not check the empty space unicode(\u0021)

            int index = s.lastIndexOf(str[i]);
            if(index>retIndex){
                retIndex = index;
            }
        }
        System.out.println("RETINDEX"+retIndex);

        Pattern pattern = Pattern.compile("A|B|C");
        Matcher m = pattern.matcher(s);

        while(m.find()){
            retIndex = m.start();
            System.out.println(m.group()+" : "+m.end()+" : "+m.start());
        }

        System.out.println("REGEX RETINDEX"+retIndex);
    }
}

我得到了输出:

RETINDEX27
A : 10 : 9
C : 19 : 18
A : 24 : 23
B : 28 : 27
REGEX RETINDEX27

我只想要最大索引输出。无需执行其他三个循环。如何根据我的需要更改上述内容?lastindexOf 与正则表达式完全匹配。

谢谢

4

1 回答 1

9

You can find the last occurrence of a regex by writing a greedy match for everything before it, for example:

.*(A|B|C)

Given your test string the .* will match everything up to the last B, and you can get the B from the capturing group.

To access the capturing group use the methods that take an int argument:

    Pattern pattern = Pattern.compile(".*(A|B|C)");
    Matcher m = pattern.matcher(s);
    if (m.find()) {
        retIndex = m.start(1);
        System.out.println(m.group(1)+" : "+m.end(1)+" : "+m.start(1));
    }
于 2013-09-30T06:34:21.723 回答