下面两行代码:
System.out.println(Arrays.toString("test".split("(?<!^)")));
System.out.println(Arrays.toString("test".split("(?!^)")));
每个产生相同的输出:
[t, e, s, t]
我预计底线会产生
[, t, e, s, t]
因为它应该愿意在 之后^
和之前分裂t
。有人能指出我的想法错在哪里吗?
下面两行代码:
System.out.println(Arrays.toString("test".split("(?<!^)")));
System.out.println(Arrays.toString("test".split("(?!^)")));
每个产生相同的输出:
[t, e, s, t]
我预计底线会产生
[, t, e, s, t]
因为它应该愿意在 之后^
和之前分裂t
。有人能指出我的想法错在哪里吗?
(?!^)
匹配任何不在字符串开头的位置,就像(?<!^)
. 由于 ^
锚点没有任何长度,因此无论您向前看还是向后看都无关紧要。
想象一下这样的字符串test
where|
表示字符之间 的位置:
| t | e | s | t |
^ matches here ($ matches here)
(?!^)
在位置不匹配,0
因为正则表达式引擎在向前看 0 个字符时从此处“看到”字符串的开头
(?<!^)
在这里也不匹配,因为当向后看 0 个字符时,正则表达式引擎从这里“看到”字符串的开头