2012-02-15 60 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