我正在尝试构建一个正则表达式,将匹配字符串,当有n
或更多特定字符出现时
。字符为/
, n=2
将:
test -> false
/test -> false
/test/test -> true
/test/test/test -> true
怎么做最好?
你可以使用backreference:
(/).*1.*1
或者您可以使用捕获组:
public static void main(final String args[]) throws Exception
{
final String input = "/test/test/test";
final String toCount = "/";
final int n = 2;
System.out.println("Looking for ".concat(n + "x: "".concat(toCount).concat(""")));
System.out.println("RESULT for "".concat(input).concat("": ") + filterChars(input, toCount, n));
}
public static boolean filterChars(final String s, final String toCount, final int n)
{
// Oh boy, this is the best... string concatenation to create regex patterns... what could go wrong?
// Please... think of the children
final Pattern p = Pattern.compile("(" + toCount + ")");
final Matcher m = p.matcher(s);
int count = 0;
while (m.find())
{
count++;
}
return (n <= count);
}
您可以使用捕捉前瞻性:
/^(?=(/)(?:.*1){1,}).*/gm
演示