1

好吧,伙计们,我的大脑被炸了。我正在尝试通过替换不正确的来修复一些边界不好的 EML

--Boundary_([ArbitraryName])

线条更恰当

--Boundary_([ArbitraryName])--

行,而离开已经正确

--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(boundary) 更改为 Pattern.quote(boundary) + "$",则不会替换任何内容。如果我尝试仅使用 matcher.replaceAll("$0--") 而不是两个循环,则不会替换任何内容。什么是实现我的目标的优雅方式,为什么它有效?

4

3 回答 3

1

无需使用find();遍历匹配项。这就是其中的一部分replaceAll()

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

替换字符串中的$0是一个占位符,无论在此迭代中匹配的正则表达式。

(?im)则表达式开头的 开启 CASE_INSENSITIVE 和 MULTILINE 模式。

于 2012-02-15T03:45:31.127 回答
0

你可以尝试这样的事情:

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

然后查看字符串是否以结尾--并仅替换不结尾的字符串。

于 2012-02-15T01:41:15.110 回答
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,一定是读得太快了。(感谢指出)

于 2012-02-15T03:17:46.160 回答