2012-02-05 94 views
0

我有字符串,它是格式:JAVA正则表达式失败

;1=2011-10-23T16:16:53+0530;2=2011-10-23T16:16:53+0530;3=2011-10-23T16:16:53+0530;4=2011-10-23T16:16:53+0530;

我已经写了下面的代码从(;1=2011-10-23T16:16:53+0530;)

Pattern pattern = Pattern.compile("(;1+)=(\\w+);"); 

String strFound= ""; 
Matcher matcher = pattern.matcher(strindData); 
while (matcher.find()) { 
    strFound= matcher.group(2); 
} 

找到字符串2011-10-23T16:16:53+0530但预期它不工作。你能给我任何提示吗?

回答

1

我已经改变输入了一点,但只是为了演示原因是

你可以试试这个:

String input = " ;1=2011-10-23T16:16:53+0530; 2=2011-10-23T16:17:53+0530;3=2011-10-23T16:18:53+0530;4=2011-10-23T16:19:53+0530;"; 

Pattern p = Pattern.compile("(;\\d+?)?=(.+?);"); 
Matcher m = p.matcher(input); 

while(m.find()){ 
    System.out.println(m.group(2)); 
} 
+1

感谢尤金。你的解决方案运行良好 – user613114 2012-02-05 15:12:50

4

你能给我任何提示吗?

是的。 -:+都不是\w的一部分。

3

你必须使用正则表达式吗?为什么不打电话String.split()拆分分号边界上的字符串。然后再次调用它以等号拆分块。在这一点上,你将有一个整数和字符串形式的日期。从那里你可以parse字符串date

import java.text.ParseException; 
import java.text.SimpleDateFormat; 
import java.util.Date; 

public final class DateScan { 
    private static final String INPUT = ";1=2011-10-23T16:16:53+0530;2=2011-10-23T16:16:53+0530;3=2011-10-23T16:16:53+0530;4=2011-10-23T16:16:53+0530;"; 
    public static void main(final String... args) { 
     final SimpleDateFormat parser = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ"); 
     final String[] pairs = INPUT.split(";"); 
     for (final String pair : pairs) { 
      if ("".equals(pair)) { 
       continue; 
      } 
      final String[] integerAndDate = pair.split("="); 
      final Integer integer = Integer.parseInt(integerAndDate[0]); 
      final String dateString = integerAndDate[1]; 
      try { 
       final Date date = parser.parse(dateString); 
       System.out.println(integer + " -> " + date); 
      } catch (final ParseException pe) { 
       System.err.println("bad date: " + dateString + ": " + pe); 
      } 
     } 
    } 
}