【问题标题】:Regex fails in extracting date from larger string正则表达式无法从较大的字符串中提取日期
【发布时间】:2017-02-22 09:44:29
【问题描述】:
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 中。

【问题讨论】:

  • 您可以添加示例输入吗?
  • String word = "e 重要的事情要记住;关于这个 Java 匹配。方法是你的正则表达式必须'匹配 28-3-2014 到 28-3-2017 整行。具体来说,一个regex ) 模式,如下所示;当您处理较大的输入文本行时,将无法使用 match 方法";它从上面的字符串中提取日期,但它不适用于包含相同格式日期的简历。如果日期像 2 年或 2 年 2 个月,它工作正常
  • 当正则表达式不匹配时,简历字符串有多大?
  • 我没听懂你。简历有两张长,我将它存储在字符串简历中并尝试匹配它。
  • 除了正则表达式之外,还有其他方法可以识别较大字符串中的日期吗? @freedev

标签: java regex date parsing


【解决方案1】:

如果您需要将这些日期与应用的任何格式相匹配,则需要在正则表达式中考虑更多空格和任何其他文本:

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"

希望这会有所帮助!

【讨论】:

  • 我尝试了你的方法,但它返回 null。如果我在单独的 java 类中尝试它,它正在执行但不在我的类中。为什么? @vagelis
  • 我认为这很简单:1) 确保resume 是包含换行符 的文本。 2)用Matcher m = Pattern.compile("<REGEX>").matcher("")之类的东西准备Matcher(我的答案是错误的,我会纠正它)。 3) 使用BufferedReader - StringReader 组合逐行提供简历。
  • 我可以使用 nlp 吗?如果有怎么办?
  • @priya 你所说的“nlp”到底是什么意思??
猜你喜欢
  • 2016-02-28
  • 1970-01-01
  • 1970-01-01
  • 2012-02-15
  • 1970-01-01
  • 2011-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多