javaregexsubstring

Is their any method to find the size of find method of matcher class?? in java


I have to find the size of matched substring.

For example

string s="2---3"
     Pattern p=Pattern.compile("-+");
 Matcher m=p.matcher(lst_str.get(i));
if(m.find()) // answer  is 3* 


if String s="2--2" // then answer is 2

How can I find the size of that substring which is matched?


Solution

  • Just use the length property of each string match:

    String s = "2---3";
    Pattern p = Pattern.compile("-+");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println("MATCH: " + m.group(0) + ", with length = " + m.group(0).length());
    }
    

    If you only have to do this one string at a time, and you want a one-liner, here is a way:

    String s = "2---3";
    int lengthOfMatch = s.length() - s.replaceAll("-+", "").length();