我正在尝试解决 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
我正在尝试使用正则表达式解决此问题,但我不确定如何处理 xyz 前面没有直接加上句点
的要求。
对于没有约束的问题,我的解决方案是这样的:
public boolean xyzThere(String str) {
return str.matches(".*xyz.*");
}
知道如何使用正则表达式处理上述约束吗?
最佳答案
否定字符类应该可以解决问题:str.matches(".*(?:^|[^.])xyz.*")
这里我们使用非捕获组 (?:^|[^.])
来确保我们匹配字符串 ^
的开头,或者在任何不是句点的位置 [^.]
关于java - 仅当字符未直接包含在所需字符串之前时,正则表达式才匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13441952/