user3721503
user3721503

Reputation:

Iterate Matcher Regex Java

I would like given a input String, iterate every substring of this String that contain a pattern, then apply to these substrings another pattern, and replace that part in some way. This is the code:

public static String parseLinkCell1NoLost(String cell) {

    String link = cell;
    Pattern catPattern = Pattern.compile("\\{\\{(.*?)\\}\\}", Pattern.MULTILINE);
    Matcher matcher = catPattern.matcher(cell);
    while (matcher.find()) {
        Pattern newP = Pattern.compile("\\{\\{nowrap|(.*?)\\}\\}", Pattern.MULTILINE);
        Matcher m = newP.matcher(cell);

        if (m.matches()) {
            String rest = m.group(0);
            String prov = m.group(1);
            String[] temp = prov.split("\\|");
            if (temp == null || temp.length == 0) {
                return link;
            } else {
                link = link.replace(rest, temp[1]);
            }
        }

    }
    return link;
}

The problem is that I cannot get the substring that matches every matcher.find(). So if I have like input "{{nowrap|x}} {{nowrap|y}}" I would like to iterate two times and get the substring {{nowrap|x}} in the first while, and {{nowrap|y}} in the second. Thanks in advance.

Upvotes: 1

Views: 3597

Answers (1)

tuempl
tuempl

Reputation: 109

public static String parseLinkCell1NoLost(String cell) {
    String link = cell;
    Pattern catPattern = Pattern.compile("\\{\\{(.*?)\\}\\}", Pattern.MULTILINE);
    Matcher matcher = catPattern.matcher(cell);
    while (matcher.find()) {
        Pattern newP = Pattern.compile("\\{\\{nowrap\\|(.*?)\\}\\}", Pattern.MULTILINE);
        Matcher m = newP.matcher(matcher.group(0));

        if (m.matches()) {
            String rest = m.group(0);
            String prov = m.group(1);
            link = link.replace(rest, prov);
        }
    }
    return link;
}

Two small mistakes:

  • in the loop you should use matcher.group(0) to only use your match not the whole cell in every iteration
  • you need to escape the | symbol in a regex
  • once that is corrected the replace(..) can be simpiflied as well

Upvotes: 2

Related Questions