2

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
ledba
  • 33
  • 3

1 Answers1

2

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)
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563