Print regex matches in java

前端 未结 2 515
悲&欢浪女
悲&欢浪女 2020-12-03 15:57

So I have an IP address as a string. I have this regex (\\d{1-3})\\.(\\d{1-3})\\.(\\d{1-3})\\.(\\d{1-3}) How do I print the matching groups?

Thanks!

2条回答
  •  青春惊慌失措
    2020-12-03 16:22

    If you use Pattern and Matcher to do your regex, then you can ask the Matcher for each group using the group(int group) method

    So:

    Pattern p = Pattern.compile("(\\d{1-3}).(\\d{1-3}).(\\d{1-3}).(\\d{1-3})"); 
    Matcher m = p.matcher("127.0.0.1"); 
    if (m.matches()) {   
      System.out.print(m.group(1));  
      // m.group(0) is the entire matched item, not the first group.
      // etc... 
    }
    

提交回复
热议问题