从字符串中提取随机格式化的年份

时间:2019-06-20 02:32:33

标签: java regex

我正在尝试检测字符串中的年份。我看过很多其他先前提出的问题,但是找不到解决随机格式的问题。假设我正在寻找2001福特Explorer的零件,并且我想过滤结果以删除那年不是的零件。我可能会遇到以下年份格式。我以为String.contains(“ 01”)可以,但是也可以匹配2010,并且无法解决我搜索的年份根本不在字符串中,而是介于其他年份之间的问题。一个正则表达式是否可以涵盖所有这些情况?

  • 适合2001 Ford Explorer。
  • 适合1997-2002年福特Explorer。
  • 适合01 Ford Explorer。
  • 01福特Explorer。
  • 适合97-02 Ford Explorer。
  • 通过97或02福特资源管理器安装。

尝试

public Boolean filterResult(String str, String expectedYear){
if(str.contains("expectedYear") && (str.indexOf(expectedYear)-1 !=2 || 
str.indexOf(expectedYear) == 0){
    return true;
}else{
    return false;
}
}

如果2010返回false。如果前一位数字是空格或破折号,并且ExpectedYear落在字符串的开头,则返回true。 没有提及预期的两年之间。

2 个答案:

答案 0 :(得分:0)

您可以使用此正则表达式:

(\d{4}|\d{2}-\d{2}|\d{2})

但是,这只会检测模式是否匹配。您将需要添加更多逻辑以确保其有效。

在以下位置进行检查:https://rubular.com

enter image description here

答案 1 :(得分:0)

可以用Java如下完成

Pattern patt = Pattern.compile("(?:Fits )?(97|1997)?(?:[^0-9]+)?(01|02|200[12]) Ford Explorer.");
// add code to iterate lines
String s = "Fits 1997-2002 Ford Explorer.";
Matcher m = patt.matcher(s);
if(m.matches()){
    if(m.group(1) != null){
        //validate year 1997
    }
    if(m.group(2) != null){
        //validate year 2002
    }
}
相关问题