我正在使用MatcherJava中的正则表达式捕获组,IllegalStateException尽管我知道表达式匹配,但它仍然会抛出一个组.
这是我的代码:
String safeName = Pattern.compile("(\\.\\w+)$").matcher("google.ca").group();
Run Code Online (Sandbox Code Playgroud)
我期望在正则表达式中捕获组safeName被.ca捕获,但我得到:
IllegalStateException:找不到匹配项
我也试图与.group(0)和.group(1)而发生同样的错误.
根据该文件group(),并group(int group):
捕获组从左到右编制索引,从1开始.组零表示整个模式,因此表达式
m.group(0)相当于m.group().
我究竟做错了什么?
Matcher是辅助类,它处理迭代数据以搜索匹配正则表达式的子字符串.整个字符串可能包含许多可匹配的子字符串,因此通过调用group()您无法指定您感兴趣的实际匹配项.要解决此问题,Matcher允许您迭代所有匹配的子字符串然后使用你感兴趣的部分.
所以在你可以使用之前,group你需要让Matcher迭代你的字符串以find()匹配你的正则表达式.要检查正则表达式是否匹配整个String,我们可以使用matches()方法而不是find().
一般来说,找到我们正在使用的所有匹配的子串
Pattern p = Pattern.compiler("yourPattern");
Matcher m = p.matcher("yourData");
while(m.find()){
String match = m.group();
//here we can do something with match...
}
Run Code Online (Sandbox Code Playgroud)
由于您假设要查找的文本只在字符串中存在一次(在其末尾),您不需要使用循环,但简单if(或条件运算符)应该可以解决您的问题.
Matcher m = Pattern.compile("(\\.\\w+)$").matcher("google.ca");
String safeName = m.find() ? m.group() : null;
Run Code Online (Sandbox Code Playgroud)