Java正则表达式负查找
我有以下Java代码:Java正则表达式负查找,java,regex,regex-lookarounds,Java,Regex,Regex Lookarounds,我有以下Java代码: Pattern pat = Pattern.compile("(?<!function )\\w+"); Matcher mat = pat.matcher("function example"); System.out.println(mat.find()); Pattern pat=Pattern.compile((?您的字符串的“function”一词与\w+匹配,并且前面没有“function”。查看它与什么匹配: public static void m
Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
System.out.println(mat.find());
Pattern pat=Pattern.compile((?您的字符串的“function”一词与\w+匹配,并且前面没有“function”。查看它与什么匹配:
public static void main(String[] args) throws Exception {
Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
while (mat.find()) {
System.out.println(mat.group());
}
}
因此,首先它找到函数
,它的前面没有“函数
”。然后它找到示例
,它的前面有函数e
,因此没有“函数
”
您可能希望模式匹配整个文本,而不仅仅是在文本中查找匹配项
您可以使用Matcher.matches()
执行此操作,也可以更改模式以添加开始和结束锚定:
^(?<!function )\\w+$
^(?)?
我更喜欢第二种方法,因为这意味着模式本身定义了其匹配区域,而不是由其用法定义的区域。不过,这只是一个偏好问题。注意以下两点:
- 您使用的是
find()
,对于子字符串匹配,它也会返回true
- 由于上述原因,“函数”匹配,因为它前面没有“函数”。
整个字符串永远不会匹配,因为您的正则表达式不匹配
包括空格
使用Mathcher#matches()
或^
和$
具有负前瞻性的锚定:
Pattern pat = Pattern.compile("^(?!function)[\\w\\s]+$"); // added \s for whitespaces
Matcher mat = pat.matcher("function example");
System.out.println(mat.find()); // false
我不理解添加起始字符串锚点的解决方案。这不是总是会返回真的吗,因为检查是在字符串的起始处完成的,并且起始字符串锚点之前不会有“函数”?而\\w
不可能匹配空格,所以找不到任何内容?它也不会在方法示例“。还有一个端点锚@Scratte.Yes。有。这会改变什么?
Pattern pat = Pattern.compile("^(?!function)[\\w\\s]+$"); // added \s for whitespaces
Matcher mat = pat.matcher("function example");
System.out.println(mat.find()); // false