[英]Regex fails in extracting date from larger string
Matcher m = Pattern.compile("\\d{1,2} years \\d months|\\d{1,2} years|"
+ "\\d{1,2}-\\d{1,2}-\\d{2,4}\\s+to\\s+\\d{1,2}-\\d{1,2}-\\d{2,4}").matcher(resume);
while (m.find()){
experience = m.group();
}
它適用於較小的字符串,但在這里我需要確定resume.i中提到的日期。
如果需要將這些日期與所應用的任何格式進行匹配,則需要在正則表達式中考慮更多的空格和其他任何文本:
Matcher m = Pattern.compile(
"^.*?" + // Start of line, then anything, non-greedy.
"(?:" + // Non-capturing group
"\\d{1,2}\\s*years(?:[,\\s]*\\d{1,2}\\s*months)?|" + // Years with optional months
"\\d{1,2}\\s*[\\-/]{1}\\d{1,2}\\s*[\\-/]{1}\\d{2,4}\\s*to\\s*" + // From to To, 1/2
"\\d{1,2}\\s*[\\-/]{1}\\d{1,2}\\s*[\\-/]{1}\\d{2,4}" + // From to To 2/2
")" + // Non-capturing group closes
".*$" // Anything else up to the end of the line
).matcher("");
如果您需要使用正則表達式來匹配行,則必須向Matcher
行:
BufferedReader reader = new BufferedReader(new StringReader(resume));
String line;
while ((line = reader.readLine()) != null) {
if (matcher.reset(line).matches()) {
experience = matcher.group();
}
}
示例匹配:
" 5 years"
"12 years, 10 months."
" 10/12/2010 to 3/2/12: Blah"
希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.