2011-03-05 76 views

回答

1

如果您使用的是YYYY日期格式,正则表达式^\d{4}应该工作字符串开头的任何日期。

String str = "1990s music groups"; 
boolean shouldDelete = str.matches("^\d{4}"); 
if (shouldDelete) { 
    // Delete string 
} 

如果你想匹配的字符串的任何部分之日起,只要将领先^

2

正则表达式\d{4}可能就足够了 - 它将匹配包含4个后续数字的所有字符串。您也许可以有一些更具体的情况下,如19\d{2}|20\d{2}

0
//ArrayList<String> list = .... 
String year = "1990"; 
ArrayList<String> toRemove = new ArrayList<String>(); 
for (String str:list) { 
    if (str.matches(".*"+year+".*")) { 
     toRemove.add(str); 
    } 
} 
for (String str:toRemove) list.remove(str); 
toRemove = null; 

使用的文档,删除列表,以防止java.util.ConcurrentModificationException

+0

如果你想要的任何日期使用\ d {4}像Bozho建议而不是年份变量 – RedSoxFan 2011-03-05 18:10:07

0

对于更具体的年率(1970年至2029年),我用:

Pattern pattern; 
Matcher matcher; 
String errorTag = null; 
private static final String PATTERN_YEAR = "^(197\\d{1}|198\\d{1}|199\\d{1}|200\\d{1}|201\\d{1}|202\\d{1})"; 

...

if (filter.getName().contains("YYYY")){ 
    pattern = Pattern.compile(PATTERN_YEAR); 
    matcher = pattern.matcher(filter.getValue()); 
     if(!matcher.matches()){ 
      errorTag= " *** The year is invalid, review the rate"; 


    } 
}