I am trying to create a regex for a CodingBat problem where I have to return a boolean based on if a String contains the phrase ‘xyz’, but ‘xyz’s that are prefeaced with a period don’t count. My attempted regexes so far have been:
str.matches("(?<!\\.)xyz");
str.matches("[^\\.]xyz")
but neither works the way I intend. If someone could steer me in the right direction as to get this to work, I would be thankful.
EDIT: Since someone asked for the tests:
xyzThere(“abcxyz”) → true
xyzThere(“abc.xyz”) → false
xyzThere(“xyz.abc”) → true
xyzThere(“abcxy”) → false
xyzThere(“xyz”) → true
xyzThere(“xy”) → false
xyzThere(“x”) → false
xyzThere(“”) → false
xyzThere(“abc.xyzxyz”) → true
xyzThere(“abc.xxyz”) → true
xyzThere(“.xyz”) → false
xyzThere(“12.xyz”) → false
xyzThere(“12xyz”) → true
xyzThere(“1.xyz.xyz2.xyz”) → false
matcheswill test against the entire string (implicitly adding^and$around the pattern). A quick fix is to add.*to both the beginning and the end of the pattern. Otherwise your first attempt is the correct one. The second one would fail at the beginning of the string, because it requires one non-.character (but there has to be one).This, admittedly is a bit of a hack. To do the usual regex testing against any part of the string, you need to use a bit more OOP:
(I couldn’t seem to use
importon CodingBat.)