简体   繁体   中英

Issue with finding indices of multiple matches in String with regex

I'm attempting to find the indices of multiple matches in a String using Regex (test code below), for use with external libraries.

static String content = "a {non} b {1} c {1}";
static String inline = "\\{[0-9]\\}";
public static void getMatchIndices()
{
    Pattern pattern = Pattern.compile(inline);
    Matcher matcher = pattern.matcher(content)
    while (matcher.find())
    {
        System.out.println(matcher.group());
        Integer i = content.indexOf(matcher.group());
        System.out.println(i);
    }
}

OUTPUT:

{1}
10
{1}
10

It finds both groups, but returns an index of 10 for both. Any ideas?

From http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#indexOf(java.lang.String ):

Returns the index within this string of the first occurrence of the specified substring.

Since both match the same thing ('{1}') the first occurrence is returned in both cases.

You probably want to use Matcher#start() to determine the start of your match.

You can do this with regexp. The following will find the locations in the string.

static String content = "a {non} b {1} c {1}";
static String inline = "\\{[0-9]\\}";

public static void getMatchIndices()
{
    Pattern pattern = Pattern.compile(inline);
    Matcher matcher = pattern.matcher(content);

    int pos = 0;
    while (matcher.find(pos)) {
        int found = matcher.start();
        System.out.println(found);
        pos = found +1;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM