Extract randomly formatted year from string

I’m trying to detect the year in a string. I’ve looked at a lot of other previously asked questions, but cannot find one which addresses random formats. Let’s say I’m searching for a part for a 2001 Ford Explorer and I want to filter the results to remove parts which are not for that year. I may encounter the below year formats. I thought String.contains(“01”) would be OK, but then that also matches 2010, and doesn’t address when the year I’m searching for isn’t in the string at all, but would fall between other years. Is it possible that one regex could cover all of these scenarios?

  • Fits 2001 Ford Explorer.
  • Fits 1997-2002 Ford Explorer.
  • Fits 01 Ford Explorer.
  • 01 Ford Explorer.
  • Fits 97-02 Ford Explorer.
  • Fits 97 thru(or through)02 Ford Explorer.


    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;
    }
    }

    In case of 2010 returns false. Returns true if the previous digit was a space or dash, and also if expectedYear falls at the beginning of the string.
    Doesn’t address expectedYear being between two other years.

Extract randomly formatted year from string