正则表达式中的AND运算符 [英] AND operator in regular expressions

查看:2148
本文介绍了正则表达式中的AND运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经搜索了一段时间如何在Java中的正则表达式中使用逻辑运算AND,并且失败了。

我尝试按照类似主题中的建议进行操作:

I've searched for a while how to use logical operation AND in regular expressions in Java, and have failed.
I've tried to do as recommended in similar topic:

(?=match this expression)(?=match this too)(?=oh, and this)

并且不起作用。即使是带有?=的简单示例也会返回false:

and it doesn't work. Even simple examples with ?= returns false:

String b = "aaadcd";
System.out.println(b.matches("(?=aa.*)"));

此外,我读过(表达式X)(表达式Y)应该像 X和Y 一样,但它的工作方式类似于 X或Y

我做错了什么?

Also I've read that (expression X)(expression Y) should work like X AND Y, but it works like X OR Y.
What am I doing wrong?

已添加:
试图添加。* in结束。仍然无法工作。

例如:

Added: Tried to add .* in the end. Still don't work.
For a example:

[2-9]?[0-9] { 5,9} || 1 [2-9] [0-9] {1,2} || 120 [0-9] {1,1} || 119 [0-9] = X - 如果数字小于1190则返回false

[2-9]?[0-9]{5,9}||1[2-9][0-9]{1,2}||120[0-9]{1,1}||119[0-9] = X - return false if number is less than 1190

[0-9] {1,3} || 1 [0-0] [0-9] {1,2} || 11 [0-8] [0-9] {1,1} || 119 [0-2] = Y - 如果数字则返回false大于1992年。

[0-9]{1,3}||1[0-0][0-9]{1,2}||11[0-8][0-9]{1,1}||119[0-2] = Y - return false if number is greater than 1992.

String a = "1189";
a.matches(X) // return false
a.mathes(Y)  // return true
a.matches((?=X)(?=Y).*) // return true, but should return false.

已添加:
是的,我的正则表达式不正确。我的错。问题解决了。非常感谢大家!

Added: Yep, my regexp is not correct. My bad. The problem solved. Thank everyone very much!

推荐答案

我认为你需要的是(?= X)Y


  • (?= X)匹配X,不消费它(零宽度)

  • Y 并匹配Y

  • (?=X) matches X, without consuming it (zero-width)
  • Y and matches Y

主要问题:X和Y错误,它们应该是(假设4位数):

The main problem: X and Y are wrong, they should be (assuming 4 digits):

X: 119 [0-9] | 1 [2-9] [0-9] {2} | [2-9] [0-9] {3}


  • 1190-1199,或

  • 1200-1999,或

  • 2000-9999

Y: 1 [0-8] [0-9] {2} | 19 [0-8] [0-9] | 199 [0-2]


  • 1000-1899,或

  • 1900-1980,或

  • 1990-1992

这里测试代码:

// 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));
}

这篇关于正则表达式中的AND运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆