我有很多文件正在从中检索数据,而且我遇到了日期值被其他数据包围的问题。我使用的是Java,我使用的正则表达式适用于变量string_i_currently_match
,但我需要它来匹配example_string_i_need_to_match
String example_string_i_need_to_match = "data 10/12/2010, data, data";
String string_i_currently_match = "10/12/2010,";
Pattern pattern = Pattern.compile(
"^(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d(?:,)$"
);
Matcher matcher = pattern.matcher(fileString);
boolean found = false;
while (matcher.find()) {
System.out.printf("I found the text "%s" starting at " +
"index %d and ending at index %d.n",
matcher.group(), matcher.start(), matcher.end());
found = true;
}
if(!found){
System.out.println("No match found.");
}
也许是因为我累了,但我无法匹配。任何帮助,甚至是指点,我们都将不胜感激。
编辑:为了澄清,我不想匹配data, data
,只想得到日期本身的索引。
^
符号与字符串的开头匹配,$
与字符串的结尾匹配。删除这些允许模式匹配字符串中的日期。
像这样:
"(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d(?:,)"
这将匹配您的日期:
[d]{2}/[d]{2}/[d]{4}
在你发布的内容中,你至少犯了一个错误:只匹配字符串开头的日期。
String ResultString = null;
try {
Pattern regex = Pattern.compile("\b[0-9]{2}/[0-9]{2}/[0-9]{4}\b");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
ResultString = regexMatcher.group();
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
除非我忽略了什么,否则这应该与你的约会相匹配。
请在此处查看它的工作情况:http://ideone.com/HETGU