-2

我有正则表达式,但我不知道如何在 Java 中使用它。这是Java代码,

String inputString = "he is in cairo on 20-2-20 12  and he will be here on JANUARY 20 2013  the expected time to arrived is 100: 00 ";
String pattern = " ";
Pattern pt = Pattern.compile(pattern);
Matcher m = pt.matcher(inputString);
String resultString=null;
if(m.find()) {
    resultString = m.replaceAll(" ");
}
System.out.println(resultString);

要求是:

  1. 用单个空格删除任何空格替换。
  2. 像这样的数据格式dd-mm-yyyy
  3. 如果数字之间有任何空格,则仅在数字之间将其删除。
  4. JANUARY 月份可能以这种格式出现:JAN.

预期的输出是:

he is in cairo on 20-2-2012  and he will be here on 20-01-2013  the expected time to arrived is 100:00 

我用过这个:

Matcher m = Pattern.compile("(\\d+)-(\\d+)?\\s*(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)").matcher(inputString);
String resultString=null;
String temp_str=null;
while (m.find()) {
    if (m.groupCount()==3) {
        int first = Integer.valueOf(m.group(1));
        int second = Integer.valueOf(m.group(2));
        String month = m.group(3);
        System.out.println("three parts");
        temp_str=m.replaceAll("\\1-\\2-\\3");
        System.out.println(temp_str);
    } else {
        int first = Integer.valueOf(m.group(1));
        String month = m.group(2);
        System.out.println("two parts");
       temp_str=m.replaceAll("\\1-\\2-\\3");
    }
}
4

1 回答 1

0

非常感谢我找到了如下解决方案:

Matcher m = Pattern.compile("([0-9]{1,2}) ([0-9]{1,2}) ([0-9]{4})").matcher(inputString);
String resultString = null;
String temp_str = null;
while (m.find()) {
    if (m.groupCount() == 3) {
        int first = Integer.valueOf(m.group(1));
        int second = Integer.valueOf(m.group(2));
        String month = m.group(3);
        System.out.println("three parts" + month);
        if (month.matches("Jan"))
        {
            System.out.println("three parts wael");
            temp_str = m.replaceAll(first + "-" + second + "-" + "JANUARY");
        }
        System.out.println(temp_str);
    } 
    else {
        int first = Integer.valueOf(m.group(1));
        String month = m.group(2);
        System.out.println("two parts");
        temp_str = m.replaceAll("\\1-\\2-\\3");
    }
}
于 2013-01-07T07:29:02.700 回答