简体   繁体   中英

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

(^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)*)

can I somehow get information, that actually matched

g

u

l

e

...

etc

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

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++)
         System.out.println(chars[i]);

  }

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