Reputation: 1573
Is there a easiest way to check if a string has a year in it(say a 4 digit number) and also to find the number of time a 4 digit number is present in the string.
eg "My test string with year 1996 and 2015"
Output
Has year - YES
number of times - 2
values - 1996 2015
I thought of doing a split string and check each and every word, but wanted to check if there is any effective way.
Upvotes: 1
Views: 4608
Reputation: 12744
You can use this regex:
^[0-9]{4}$
Explanation:
^ : Start anchor
[0-9] : Character class to match one of the 10 digits
{4} : Range quantifier. exactly 4.
$ : End anchor
And here a sample code:
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());
Output:
hasYear: true
number of times: 5
values: 1996 2015 1999 1900 2000
Upvotes: 6
Reputation: 4430
Since there's already a nice solution using regexes i'll present mine without regexes:
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;
}
Upvotes: 2