2010-12-03 46 views
-1

有沒有辦法使用Java正則表達式來將字符串更改爲某種格式?例如,我有一個輸入字符串,其中包含日期&時間,可以用各種分隔符輸入,我可以使用正則表達式將其更改爲使用特定的分隔符?如果可以,我該怎麼做?目前,我只是檢查與正則表達式的輸入,然後與所需的分隔符串聯在一起,一個新的字符串,像這樣:有沒有辦法用正則表達式重新格式化Java String?

Pattern dtPatt = Pattern.compile("\\d\\d\\d\\d[/\\-.]\\d\\d[/\\-.]\\d\\d[tT/\\-.]\\d\\d[:.]\\d\\d[:.]\\d\\d"); 
Matcher m = dtPatt.matcher(dtIn); 
if (m.matches()) { 
    String dtOut = dtIn.substring(0, 4) + "/" + dtIn.substring(5, 7) + "/" + 
        dtIn.substring(8, 10) + "-" + dtIn.substring(11, 13) + ":" + 
        dtIn.substring(14, 16) + ":" + dtIn.substring(17, 19); 
    // do processing with dtOut 
} else { 
    System.out.println("Error! Bad date/time entry."); 
} 

好像我應該能夠用正則表達式來做到這一點,但很多谷歌搜索,閱讀和實驗沒有產生任何有效的工作。

+0

作爲一個側面說明,取決於你把它放在哪裏,由於模式的編譯可能會變得非常低效。 – Woot4Moo 2010-12-03 16:19:03

+0

@ Woot4Moo:謝謝你的想法。在製作過程中,我會處理一個未知的 - 理論上無限的 - 日期/時間字符串的數量。 – GreenMatt 2010-12-03 16:22:53

+0

@GreenMatt在這種情況下,也許你應該偏離使用Java正則表達式並將它傳遞給一個單獨的語言,如Perl或Python。我可能會誤解,但我相信這些語言都不會被編譯,並且打開數據流將不會比重新編譯每次運行的野獸密集。 – Woot4Moo 2010-12-03 16:25:32

回答

3

請嘗試以下

Pattern dtPatt = Pattern.compile("(\\d\\d\\d\\d)[/\\-.](\\d\\d)[/\\-.](\\d\\d)[tT/\\-.](\\d\\d)[:.](\\d\\d)[:.](\\d\\d)"); 
    Matcher m = dtPatt.matcher(str); 

    if (m.matches()) 
    { 
     StringBuffer sb = new StringBuffer(); 
     m.appendReplacement(sb, "$1/$2/$3-$4:$5:$6"); 

     String result = sb.toString(); 
    } 
    else 
    { 
     System.out.println("Error! Bad date/time entry."); 
    } 

兩個變化

  • 變化的正則表達式模式有分組,使用()
  • 使用appendReplacement與$ x使用與模式匹配的特定組的替換模式。
2

我會嘗試

DateFormat DF = new SimpleDateFormat("yyyy/MM/dd-HH:mm:dd"); 

String dtIn2 = String.format("%s/%s/%s-%s:%s:%s", dtIn.split("\\D+")); 
DF.parse(dtIn2); // to validate the date produced. 
1

嘗試匹配器appendReplacement()appendTail()方法。有一個在appendReplacement()一個很好的例子:

Pattern p = Pattern.compile("cat"); 
Matcher m = p.matcher("one cat two cats in the yard"); 
StringBuffer sb = new StringBuffer(); 
while (m.find()) { 
    m.appendReplacement(sb, "dog"); 
} 
m.appendTail(sb); 
System.out.println(sb.toString()); 
相關問題