這裏的一些Java代碼應該做你想要的東西:
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^-?([^\\.]+\\.){1,2}\\((\\d+-\\d+|\\d+)|([^|]+|[^|]+)\\)$");
String[] samples = { "world.block.(1-2|1).(test1|stack)",
"test.test.(1-2|1)",
"world.(test1|stack)",
"-help.block.(1-2|1).(test1|stack)",
"-world.help",
"world.stack",
"world.block."
};
for (String sample : samples) {
Matcher matcher = pattern.matcher(sample);
System.out.println(sample + (matcher.find() ? " matched" : " failed"));
}
}
輸出是:
world.block.(1-2|1).(test1|stack) matched
test.test.(1-2|1) matched
world.(test1|stack) matched
-help.block.(1-2|1).(test1|stack) matched
-world.help failed
world.stack failed
world.block. failed
唯一缺少的是範圍檢查的數字。可以添加它,但我寧願使用匹配的組,並使用數學進行範圍檢查,以避免過分複雜的正則表達式。
不清楚,你的輸入是什麼,你試圖匹配什麼? – Dalorzo 2014-09-03 18:20:39
我想你忘了告訴我們你需要什麼正則表達式來匹配 – 2014-09-03 18:22:14
,試試這個正則表達式:'(world \ .block \。\(1-2 \ | 1 \)\。\(test1 \ | stack \))|(-world \ .block \ \(1-2 \ | 1 \)\ \(TEST1 \ |。棧\)|。(世界\ .block \ \(1-2 \ | 1 \) ))|(world \。\(test1 \ | stack \))' – 2014-09-03 18:24:16