Regex only match if character is not included directly before desired string

前端 未结 2 1302
你的背包
你的背包 2021-01-17 19:46

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

相关标签:
2条回答
  • 2021-01-17 20: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 [^.]

    0 讨论(0)
  • 2021-01-17 20:24

    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.

    0 讨论(0)
提交回复
热议问题