作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有以下 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/
我正在尝试获得一个按钮,按下该按钮时会改变颜色。当再次按下时,它应该变回原来的颜色。我究竟做错了什么? 我的模板中的按钮: export default { data: {
我是一名优秀的程序员,十分优秀!