2013-01-07 75 views
-2

我有正則表達式,但我不知道如何在Java中使用它。這是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. 1月份可能會採用這種格式: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"); 
    } 
} 
+1

請不要問我們來轉換代碼。因爲這樣,你已經使回答者知道轉換中使用的兩種語言。而只是告訴你想做什麼?您的輸入和預期輸出。 –

+0

好的。非常感謝你 –

回答

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"); 
    } 
}