Oleg Gritsak Oleg Gritsak - 1 year ago 70
Java Question

Get matched pattern value in java regex

I'm doing some transliteration with java and everything works great, but it would be nice to have matched pattern. Is it possible?

For example:

for surname GULEVSKAIA I generate such pattern


can I somehow get information, that actually matched







As you can see, sometimes it is NOT one letter.

Answer Source

You may achieve this , once pattern is matched , retrive the macthed string using group() method of Matcher class passing 0 as value. then convert that string to chars array and print those characters like below

  String line = "gulevskaia";
  String pattern = "(^g+(yu|u|y)l+(io|e|ye|yo|jo|ye)(v|b|w)+(s|c)+(k|c)+a(ya|ia|ja|a|y)(a)*)";

  Pattern r = Pattern.compile(pattern);
  Matcher m = r.matcher(line);

  if (m.find( )) {
     System.out.println("Found value: " + m.group(0) );
     char chars[] =m.group(0).toCharArray();
     for(int i=0;i<chars.length;i++)