2012-02-15 61 views
1

好的夥計們,我的大腦被炸了。我試圖用更合適的Java替換所有正則表達式有類似的結果

--Boundary_([ArbitraryName])-- 

線替換不正確的

--Boundary_([ArbitraryName]) 

線修復了一些EML中壞的界限,而只留下已經是正確的

--Boundary_([ThisOneWasFine])-- 

線。我把整條消息作爲一個字符串存儲在內存中(是的,這很醜陋,但是如果JavaMail試圖解析這些消息就會死掉),並且我正在嘗試對它進行replaceAll。這是我能得到的最接近的。

//Identifie bondary lines that do not end in -- 
String regex = "^--Boundary_\\([^\\)]*\\)$"; 
Pattern pattern = Pattern.compile(regex, 
    Pattern.CASE_INSENSITIVE | Pattern.MULTILINE); 
Matcher matcher = pattern.matcher(targetString); 
//Store all of our unique results. 
HashSet<String> boundaries = new HashSet<String>(); 
while (matcher.find()) 
    boundaries.add(s); 
//Add "--" at the end of the Strings we found. 
for (String boundary : boundaries) 
    targetString = targetString.replaceAll(Pattern.quote(boundary), 
     boundary + "--"); 

這與

--Boundary_([WasValid])---- 

然而更換所有的有效

--Boundary_([WasValid])-- 

線的明顯的問題,這是我已經得到了甚至進行更換隻設置。如果我嘗試將Pattern.quote(邊界)更改爲Pattern.quote(boundary)+「$」,則不會替換。如果我嘗試使用matcher.replaceAll(「$ 0--」)而不是兩個循環,則不會替換任何內容。什麼是實現我的目標的優雅方式,以及它爲什麼起作用?

回答

1

有沒有必要遍歷與find();這是replaceAll()所做的一部分。

s = s.replaceAll("(?im)^--Boundary_\\([^\\)]*\\)$", "$0--"); 

在替換字符串$0無論是正則表達式在本次迭代匹配的佔位符。

在正則表達式開頭的(?im)打開CASE_INSENSITIVE和MULTILINE模式。

+0

謝謝;即使我以前在$ 0的嘗試沒有做到這一點。除了現在我非常抓撓我的頭,因爲我不確定我是怎麼搗亂它的,但是我會在那個時候記下那一個,讓他感到極度疲勞,並且稱這個完成。接受這個最優雅和最好解釋的(但是,其他人)。 – 2012-02-15 05:16:34

0

你可以嘗試這樣的事情:

String regex = "^--Boundary_\\([^\\)]*\\)(--)?$"; 

然後看看字符串以--結束,只更換那些沒有。

0

假設所有的字符串都在有自己的在線工作的: "(?im)^--Boundary_\\([^)]*\\)$"

示例腳本:

String str = "--Boundary_([ArbitraryName])\n--Boundary_([ArbitraryName])--\n--Boundary_([ArbitraryName])\n--Boundary_([ArbitraryName])--\n"; 
System.out.println(str.replaceAll("(?im)^--Boundary_\\([^)]*\\)$", "$0--")); 

編輯:從JavaScript改爲Java的,必須讀得太快(感謝。指出它)

+0

你在暗示他使用JavaScript腳本引擎? – 2012-02-15 03:49:10