2

Is it possible to implement a logical AND in Java's Regexp? If the answer is yes, how can that be achieved?

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Is this considered a single regex?
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.