我正在嘗試構建一個匹配字串的正則運算式,當n特定字符出現或多次出現時(字串中的任何位置)。
例如,字符是/,并且 n=2
會給:
test -> false
/test -> false
/test/test -> true
/test/test/test -> true
如何最好地做到這一點?
uj5u.com熱心網友回復:
您可以使用反向參考:
(/).*\1.*\1
uj5u.com熱心網友回復:
或者您可以使用捕獲組:
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);
}
uj5u.com熱心網友回復:
您可以使用捕獲前瞻:
/^(?=(\/)(?:.*\1){1,}).*/gm
演示
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/340858.html
標籤:正则表达式
