2013-01-07 5 views
-2

J'ai une expression régulière mais je ne sais pas comment l'utiliser en Java. Voici le code Java,Expression régulière en 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); 

Les exigences sont les suivantes:

  1. supprimer les espaces de remplacement par un espace unique.
  2. le format de données comme ceci dd-mm-yyyy.
  3. S'il y a des espaces entre les nombres, supprimez-le juste entre les nombres. Le mois de janvier peut-être venir dans ce format: JAN.

Le résultat attendu est:

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 

Je l'ai utilisé ceci:

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

S'il vous plaît ne pas demander nous pour convertir le code. Parce qu'avec cela, vous avez lié le répondant à connaître les deux langues utilisées dans la conversion. Plutôt juste dire ce que vous voulez faire? Votre entrée, et la sortie attendue. –

+0

ok. merci beaucoup pour vous –

Répondre

0

Un grand merci, j'ai trouvé la solution comme suit:

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