简体   繁体   English

他们有什么方法可以找到匹配器 class 的查找方法的大小吗? 在 java

[英]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.我必须找到匹配的 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?如何找到匹配的 substring 的大小?

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM