嘿我正在寻找正常工作的正则表达式
我尝试了类似^([-])?(([(])?[-|]{0}[a-zA-z0-9|]([)])?([.])?)+$
之类的东西,但它并不是很好。
它应匹配:
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.
所有文字都是例子!
答案 0 :(得分:0)
这里有一些应该做你想做的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
唯一缺少的是范围检查数字。可以添加它,但我宁愿使用匹配组并使用数学进行范围检查,以避免过度复杂的正则表达式。