检查String中是否有一年

Jee*_*ppp 1 java string

是否有最简单的方法来检查字符串中是否有一年(比如4位数字),还可以找到字符串中存在4位数字的时间.

例如 "My test string with year 1996 and 2015"

产量

Has year - YES number of times - 2 values - 1996 2015

我想做一个拆分字符串并检查每个单词,但想检查是否有任何有效的方法.

Pat*_*ick 6

你可以使用这个正则表达式:

^[0-9]{4}$
Run Code Online (Sandbox Code Playgroud)

说明:

^     : Start anchor
[0-9] : Character class to match one of the 10 digits
{4} : Range quantifier. exactly 4.
$     : End anchor
Run Code Online (Sandbox Code Playgroud)

这里有一个示例代码:

    String text = "My test string with year 1996 and 2015 and 1999, and 1900-2000";
    text = text.replaceAll("[^0-9]", "#"); //simple solution for replacing all non digits. 
    String[] arr = text.split("#");

    boolean hasYear = false;
    int matches = 0;
    StringBuilder values = new StringBuilder();

    for(String s : arr){
        if(s.matches("^[0-9]{4}$")){
            hasYear = true;
            matches++;
            values.append(s+" ");
        }
    }
    System.out.println("hasYear: " + hasYear);
    System.out.println("number of times: " + matches);
    System.out.println("values: " + values.toString().trim());
Run Code Online (Sandbox Code Playgroud)

输出:

hasYear: true
number of times: 5
values: 1996 2015 1999 1900 2000
Run Code Online (Sandbox Code Playgroud)