好的伙计们,我的大脑被炸了。我试图用更合适的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--”)而不是两个循环,则不会替换任何内容。什么是实现我的目标的优雅方式,以及它为什么起作用?
谢谢;即使我以前在$ 0的尝试没有做到这一点。除了现在我非常抓挠我的头,因为我不确定我是怎么捣乱它的,但是我会在那个时候记下那一个,让他感到极度疲劳,并且称这个完成。接受这个最优雅和最好解释的(但是,其他人)。 – 2012-02-15 05:16:34