Is it possible to implement a logical AND in Java's Regexp? If the answer is yes, how can that be achieved?
1 Answer
Logical ANDs in regexes are made up of a sequence of stacked lookahead assertions. For example:
(?=^.*foo)
(?=^.*bar)
(?=^.*glarch)
will match any string that contains all three of "foo", "bar", and "glarch", in any order, and even though some should overlap. (This assumes a customary interpretation of ^ and ..)
Of course, this property is not peculiar to Java.
2 Comments
EpsilonVector
Is this considered a single regex?
tchrist
@EpsilonVector: Sure! It is if you use it that way. I’ve put the separate subregexes each on their own line for legibility. That would in Java require that one use either a leading
(?x) or Pattern.COMMENTS on the compilation so that the newline doesn’t count. Or you could simple catenate the three pieces directly using + or some other joining mechanism. I can update the answer to a full example in Java if you want, but it might help if you would showed me what the things you wanted AND’d together actually are.