有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java检查字符串中是否有年份

是否有一种最简单的方法来检查字符串中是否包含年份(例如4位数字),以及查找字符串中出现4位数字的时间

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

输出

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

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


共 (2) 个答案

  1. # 1 楼答案

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

    ^[0-9]{4}$
    

    说明:

    ^     : Start anchor
    [0-9] : Character class to match one of the 10 digits
    {4} : Range quantifier. exactly 4.
    $     : End anchor
    

    下面是一个示例代码:

        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());
    

    输出:

    hasYear: true
    number of times: 5
    values: 1996 2015 1999 1900 2000
    
  2. # 2 楼答案

    既然已经有一个很好的使用正则表达式的解决方案,我将展示我的不使用正则表达式的解决方案:

    private static List<String> findNumbers(String searchStr) {
        List<String> list = new ArrayList<String>();
        int numbers = 0, first = -1;
        for (int i = 0; i < searchStr.length(); i++) {
            char ch = searchStr.charAt(i);
            if (ch >= '0' && ch <= '9') {
                first = first < 0 ? i : first;
                numbers++;
            } else { 
                if (numbers == 4)
                    list.add(searchStr.substring(first, i));
                numbers = 0;
                first = -1;
            }
        }
        if (numbers == 4)
            list.add(searchStr.substring(first, first+4));
        return list;
    }