我正在尝试提取以下字符串中的数字:
2014年9月29日
我目前使用的代码:
Pattern p = Pattern.compile("([0-9]{2})/([0-9]{2})/([0-9]{4})");
Matcher m = p.matcher(startDatepicker);
String startYear = m.group(3);
String startMonth = m.group(1);
String startDay = m.group(2);
startDatepicker
包含:09/29/2014
但是,我没有收到任何匹配项。我还尝试使用 \\
转义正斜杠,但这也不起作用。
我错过了什么吗?
感谢您的帮助。
最佳答案
在访问匹配的组之前,您需要在匹配器上调用find()
,并检查它是否找到了匹配项:
Pattern p = Pattern.compile("([0-9]{2})/([0-9]{2})/([0-9]{4})");
Matcher m = p.matcher(startDatepicker);
if (!m.find()) {
return;
}
String startYear = m.group(3);
String startMonth = m.group(1);
String startDay = m.group(2);
调用 m.find()
将匹配器定位到第一个匹配项。
关于java - 匹配器未找到匹配项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25735613/