[英]Parse regex with regex
我有模式[a-z0-9]{9}|[a-z0-9]{11}
在這里,我必須解析該正則表達式以獲得 9 和 11 以備將來“您必須輸入 9 或 11 個符號”的消息
我也有正則表達式
[a-z0-9]{9}
[a-z0-9]{9,}
[a-z0-9]{9,11}
我需要編寫一些方法,它可以解析所有字符串以獲取可用符號的數量。
我做了
Pattern.compile(".*\\\\{(\\\\d+)(,?)(\\\\d*)\\\\}(\\\\|.*\\\\{(\\\\d+)\\\\})?");
它只在我的第一個模式中找到最后一個數字。 但其他不認識。
如何檢查所有字符串?
更新:我不明白,但在 Java 第一個模式中,答案\\{(\\d+)(?:,(\\d*))?\\}
不匹配,但找到 3 個我的字符串。 但是它沒有找到第一個和最長的字符串。
匹配和查找有什么區別? 為什么該模式可以在網絡中找到匹配項,而在 Java 中卻不能? 有時我會做matcher.find(); // return 2 matcher.group(1); // No match found exception
matcher.find(); // return 2 matcher.group(1); // No match found exception
這個正則表達式應該對你[^\\\\](?:\\\\\\\\)*\\{(\\d+)(?:,(\\d*))?\\}
: [^\\\\](?:\\\\\\\\)*\\{(\\d+)(?:,(\\d*))?\\}
。
[^\\\\](?:\\\\\\\\)*
解決了斜線轉義的情況。
下面是Java代碼示例:
public static void main(String[] args) {
Pattern p = Pattern.compile("[^\\\\](?:\\\\\\\\)*\\{(\\d+)(?:,(\\d*))?\\}");
String testInput = "[a-z0-9]{1,2}|[a-z0-9]{3,}|[a-z0-9]{4}";
Matcher matcher = p.matcher(testInput);
while (matcher.find()){
System.out.println("Next matching found:");
if(matcher.group(2) == null){
System.out.println("Strict: " + matcher.group(1));
}else {
System.out.println("Min: "
+ matcher.group(1)
+ ", Max: "
+ ("".equals(matcher.group(2)) ? "Infinte" : matcher.group(2)));
}
}
}
輸出:
Next matching found:
Min: 1, Max: 2
Next matching found:
Min: 3, Max: Infinte
Next matching found:
Strict: 4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.