我已经寻找了一段时间如何在Java中使用逻辑运算和正则表达式,但都失败了。
我试着按照类似主题中的建议去做:
(?=match this expression)(?=match this too)(?=oh, and this)但它不起作用。即使是使用?=的简单示例也会返回false:
String b = "aaadcd";
System.out.println(b.matches("(?=aa.*)"));我还读到过(expression X)(expression Y)应该像X AND Y一样工作,但它也像X OR Y一样工作。
我做错了什么?
已添加:尝试在末尾添加.*。还是不管用。
举个例子:
[2-9]?[0-9]{5,9}||1[2-9][0-9]{1,2}||120[0-9]{1,1}||119[0-9] =X-如果数字小于1190,则返回false
[0-9]{1,3}||1[0-0][0-9]{1,2}||11[0-8][0-9]{1,1}||119[0-2] =Y-如果数字大于1992,则返回false。
String a = "1189";
a.matches(X) // return false
a.mathes(Y) // return true
a.matches((?=X)(?=Y).*) // return true, but should return false.补充:是的,我的regexp不正确。是我的错。问题解决了。非常感谢大家!
发布于 2011-05-31 19:47:18
我想你需要的是(?=X)Y
(?=X)匹配X,不消耗它(zero-width)Y,匹配Y 主要问题:X和Y是错误的,它们应该是(假设4位数):
X:119[0-9]|1[2-9][0-9]{2}|[2-9][0-9]{3}
or
Y:1[0-8][0-9]{2}|19[0-8][0-9]|199[0-2]
or
的
下面是一个测试代码:
// X - return false if number is less than 1190
String X = "119[0-9]|1[2-9][0-9]{2}|[2-9][0-9]{3}";
// Y - return false if number is greater than 1992.
String Y = "1[0-8][0-9]{2}|19[0-8][0-9]|199[0-2]";
String pattern = "(?=" + X + ")" + Y;
String values = "1000 1100 1180 1189 1190 1191 1199 1200 1290 1900 1980 1989 " +
"1990 1991 1992 1993 1999 2000 3000 2991 9999";
for (String string : values.split(" ")) {
System.out.printf("\"%s\" %s%n", string, string.matches(pattern));
}发布于 2011-05-31 17:24:03
(?= 可以在上工作。
您所做的错误是您正在使用matches,但是您的正则表达式与任何内容都不匹配。
(?=是一个zero-width positive look-ahead:它不“消费”任何字符,而只是验证它的位置后面是否有与其内容匹配的内容。
因此,要么将您的matches()调用替换为Matcher.find(),要么确保您的正则表达式中有与整个字符串匹配的内容(.*是常见的候选)。
发布于 2011-05-31 17:32:55
正如约阿希姆回答的那样,在末尾添加一个.*:
String b = "aaadcd";
System.out.println(b.matches("(?=aaa)(?=.*dcd).*"));
// => true
String b = "aaaxxx";
System.out.println(b.matches("(?=aaa)(?=.*dcd).*"));
// => falsehttps://stackoverflow.com/questions/6185438
复制相似问题