Reputation: 33
I want a regular expression to match everything that does not start with X or contains Y.
I currently have the first part: ^(?!X).*$
This will match anything not starting with X. However, I can't get the second part working. I have tried the solution here:
Regex match string that starts with but does not include
but with no luck.
Test cases
Don't match on:
X
XBLABLA
Match on:
XY
BLABLA
Any ideas?
Upvotes: 2
Views: 1502
Reputation: 626929
You may use
^(?:(?!X)|.*Y).*$
See the regex demo
In Java, when using matches
, the anchors are not necessary at the start/end:
s.matches("(?s)(?:(?!X)|.*Y).*")
The (?s)
will allow matching strings containing line breaks.
Details
^
- start of string (implicit in matches
)(?:(?!X)|.*Y)
- either a position not followed with X
immediately to the right, or any 0+ chars as many as possible and then Y
.*
- the rest of the string (it is necessary if the regex is used with matches
, it is not necessary with find
as the latter does not require the full string match)$
- end of string (implicit in matches
)Upvotes: 2