AND in regular expressions

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

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

and it does not work. Even simple examples with? = Returns false:

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

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

Added: I tried to add .* At the end. Still not working.
For example:

[2-9]?[0-9]{5,9}||1[2-9][0-9]{1,2}||120[0-9]{1,1}||119[0-9] = X - returns false if the 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 - returns false if the 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: Yes, my regular expression is incorrect. To blame. The problem is resolved. Thank you all very much!

+7
source share
3 answers

I think you need (?=X)Y

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

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

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

  • 1190-1199, or
  • 1200-1999, or
  • 2000-9999

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

  • 1000-1899, or
  • 1900-1980, or
  • 1990-1992

Here is the test code:

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

(?= works .

What you are doing wrong is that you use matches , but your regular expression doesn't match anything.

(?= - a positive forecast with a zero width : it does not "consume" any characters, but simply checks that its position is followed by something that matches its content.

Thus, either replace matches() your Matcher.find() call, or make sure you have something in your regular expression that matches the entire line ( .* Is a common candidate).

+6
source

As Joachim answered, add .* the end:

 String b = "aaadcd"; System.out.println(b.matches("(?=aaa)(?=.*dcd).*")); // => true String b = "aaaxxx"; System.out.println(b.matches("(?=aaa)(?=.*dcd).*")); // => false 
+1
source

All Articles