是否有最简单的方法来检查字符串中是否有一年(比如4位数字),还可以找到字符串中存在4位数字的时间。
例如"My test string with year 1996 and 2015"
输出
Has year - YES
number of times - 2
values - 1996 2015
我想做一个拆分字符串并检查每个单词,但想检查是否有任何有效的方法。
答案 0 :(得分:6)
您可以使用此正则表达式:
^[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
答案 1 :(得分: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;
}