jeudi 15 novembre 2018

Java Matcher's group() method not working [duplicate]

I'm trying to find the string portion using group method available in Java's Matcher class suing regex. The problem is comment line 4 and executing its throwing java.lang.IllegalStateException: No match found but if I uncomment line 4 and then execute then it's giving result as expected. I am not sure what is going on here. Can any please provide some explanation?

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

public class RegexMasking {

  public static void main(String[] args) {

    String regex = "(?ms)<Password>(?<abc>.*?)</Password>"; //line 1
    String string = "<User>TestUser</User>\n"
            + "<Password>TestPassword</Password>\n"
            + "<Email>TestEmail</Email>";
    String subst = "----";

    Pattern pattern = Pattern.compile(regex);//line 2
    Matcher matcher = pattern.matcher(string);//line 3
    String result = matcher.replaceFirst(subst); //line 4
    String matchedString = matcher.group("abc"); //line 5
    System.out.println("Matched String: " + matchedString); //line 6
  }
}

Full stack trace while exception

Exception in thread "main" java.lang.IllegalStateException: No match found
at java.util.regex.Matcher.getMatchedGroupIndex(Matcher.java:1314)
at java.util.regex.Matcher.group(Matcher.java:572)
at com.nationwide.RegexMasking.main(RegexMasking.java:24)

Any suggestions and explanation are welcome. Thank you

Aucun commentaire:

Enregistrer un commentaire