0

所以现在我有这个方法:

public static String convert(String str) {

    if (str.equals("# "))
    System.out.println(" ");

Pattern pattern = Pattern.compile("(#+[^#]+)");
Matcher matcher = pattern.matcher(str);

while (matcher.find()) {
    String str1 = matcher.group(1);
    int n = str1.length() - str1.replaceFirst("#+", "").length();
System.out.println("<h" + n + ">" + str1.substring(n) + "</h" + n + ">");
}

return ("");
}    

当我输入 ###Le Monde # 时,它会给出 < h3>Le Monde </h3> < h1> </h1>。我希望它忽略“le monde”之后的#。基本上,我希望算法忽略一系列 # 后跟空格或返回键。我究竟做错了什么?

4

1 回答 1

1

在获得下一个匹配项 (str1) 后添加另一行,因此:

String str1 = matcher.group(1);
if(str1.replaceFirst("#+", "").length() == 0 || str1.replaceFirst("#+", "").matches("[\\s]+")) continue;

这将忽略任何空格匹配。

于 2012-10-22T00:03:52.350 回答