10

I'm trying to solve this CodingBat problem:

Return true if the given string contains an appearance of "xyz" where the xyz is not directly preceeded by a period (.). So "xxyz" counts but "x.xyz" does not.

xyzThere("abcxyz") → true
xyzThere("abc.xyz") → false
xyzThere("xyz.abc") → true

I'm trying to solve this with a regex, but I'm unsure how to handle where the xyz is not directly preceeded by a period requirement.

My solution for the problem without the constraint is this:

public boolean xyzThere(String str) {
    return str.matches(".*xyz.*");
}

Any idea how to handle the said constraint with a regex?

1
  • Negative lookbehind is what you are looking for. But to use it you also need to know about it limits Commented Nov 18, 2012 at 16:26

2 Answers 2

13

A negated character class should do the trick: str.matches(".*(?:^|[^.])xyz.*")

Here we're using a non capturing group (?:^|[^.]) to ensure that we match either at the start of the string ^, or at any position that isn't a period [^.]

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

Comments

8

I personally used this solution, but there are quite a number of other variants:

str.matches("(.*[^.])?xyz.*")

I just make sure that if there is anything in front of xyz, then the period . does not immediately precede.

You can also write a look-behind solution:

str.matches(".*(?<!\\.)xyz.*");

(?<! ) part is negative lookbehind, and \\. (literal period) is the pattern that we want to check against.

7 Comments

@KelvinMackay: Java matches assume anchor.
I pass the test cases on CodingBat, though. Please provide test case that fails the code.
@KelvinMackay: The thing is the regex I wrote are equivalent to the version that has ^ in front and $ at the back, courtesy of matches in String class. Your argument would be correct if the anchors were not assumed.
I understand that, but that's not why it doesn't work when I try it. Anyway, it's not important - it works on CodingBat so your answer's correct :)
I do believe that forces a compile every time using str.matches(arbitraryRegEx);
|

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.