gpt4 book ai didi

Java RegEx 负向后视

转载 作者:太空狗 更新时间:2023-10-29 22:38:06 26 4
gpt4 key购买 nike

我有以下 Java 代码:

Pattern pat = Pattern.compile("(?<!function )\\w+");
Matcher mat = pat.matcher("function example");
System.out.println(mat.find());

为什么 mat.find() 返回 true?我使用了负向后视,example 前面是 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());
}
}

输出:

function
xample

所以它首先找到 function,它前面没有“function”。然后它找到 xample,它前面是 function e,因此不是“function”。

大概您希望模式匹配整个文本,而不仅仅是在文本中找到匹配项。

您可以使用 Matcher.matches() 执行此操作,也可以更改模式以添加开始和结束 anchor :

^(?<!function )\\w+$

我更喜欢第二种方法,因为它意味着模式本身定义了它的匹配区域,而不是它的用法定义的区域。然而,这只是一个偏好问题。

关于Java RegEx 负向后视,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18015812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com