java - 为什么 regex="" (一个空模式)在每个字符位置都匹配?
问题描述
我有regex=""
一个String str="stackoveflow";
我不明白为什么它匹配字符串中的每个字符。你能给我解释一下吗?
public class test {
public static void main(String[] args){
Console console = System.console();
String str="stackoveflow";
Pattern pattern = Pattern.compile("");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
console.format("I found the text" +
" \"%s\" starting at " +
"index %d and ending at index %d.%n",
matcher.group(),
matcher.start(),
matcher.end());
}
}
}
输出是:
I found the text "" starting at index 0 and ending at index 0. I found the text "" starting at index 1 and ending at index 1. I found the text "" starting at index 2 and ending at index 2. I found the text "" starting at index 3 and ending at index 3. I found the text "" starting at index 4 and ending at index 4. I found the text "" starting at index 5 and ending at index 5. I found the text "" starting at index 6 and ending at index 6. I found the text "" starting at index 7 and ending at index 7. I found the text "" starting at index 8 and ending at index 8. I found the text "" starting at index 9 and ending at index 9. I found the text "" starting at index 10 and ending at index 10. I found the text "" starting at index 11 and ending at index 11. I found the text "" starting at index 12 and ending at index 12.
解决方案
Pattern("")
匹配由零个字符组成的字符串。您可以在字符串的每个位置找到其中一个。
注意:如果您更改find
为match
,您应该会发现没有匹配项。(与match
模式需要匹配整个输入,而整个输入不匹配零字符序列。)
在您编辑问题之前,您的模式是Pattern("e*")
. 这意味着字符的零次或多次重复'e'
。通过上面的逻辑,您可以在输入中的每个字符位置“找到”其中一个。
推荐阅读
- javascript - Jquery选择选项值并添加一个数值并显示结果
- swift - 在 Swift 中使用 Rand 进行测试
- c - 如何纠正开关中结构的错误
- php - 在magento市场上传模块时出现清漆缓存缺失问题
- python - 将 2 个列表汇总到另一个列表中
- php - 如何使用 GET 方法使用面向对象的 php 生成随机骰子数?
- macros - 宏与接受表达式的函数
- sql - Oracle WITH 子句限制
- ios - 如何显示打开自定义 iOS 相机编辑应用程序以从任何 Web 浏览器或第三方应用程序捕获图片的选项?
- python - 对于没有标题行的 csv,如何从 pandas.Series.from_csv 切换到 pandas.read_csv?