我一直在尝试使用正则表达式来实现这一点,但我总是失败,所以也许对此更有经验的人可以提供帮助?
如何呈现类似于任何网络浏览器呈现 html 字符串的方式的字符串? HTML 示例:
<html>
Hel
lo
how
are you
</html>
渲染后:
Hel lo how are you
我希望它是
Hello how are you
所以与 html 的区别在于,没有显式空格的换行符会被删除。在 java 中这个字符串看起来像这样:
\tHel\nlo \n how\n are you
我当前的解决方案:
// remove linebreaks and tabs and any leading or trailing whitespace
// this is necessary to avoid converting \t or \n to a space
script = script.replaceAll("\\s+\n\\s+", "");
script = script.replaceAll("\\s+\t\\s+", "");
// remove any length of whitespace and replace it with one
script = script.replaceAll("\\s+", " ");
// rewmove leading and trailing whitespaces
script = script.trim();
只有一个问题: 如果我有一行尾随空格后跟换行符和一些其他文本,则尾随空格将被删除:
Hello \nhow are you?
将减少为
Hellohow are you
因此,使用下划线 (_) 作为空格标记,以下内容应该是正确的:
_ = _
__ = _
\t\n_ = _
_\t\n = _
\t_\n = _
_\t_\n_ = _
\n = // nothing
\t = // nothing
\t\n = // nothing
我需要使用replaceAll(regex, string)的什么组合?
最佳答案
我认为 - 考虑到您当前的示例 - 您想将替换功能更改为:
// remove any newlines or tabs (leading or trailing whitespace doesn't matter)
script = script.replaceAll("(\\\t|\\\n)", "");
// boil down remaining whitespace to a single space
script = script.replaceAll("\\s+", " ");
script = script.trim();
这当然会导致类似的情况
Hello\nhow are you?
减少到
Hellohow are you?
但这是您的要求的固有结果。
关于Java 几乎像 HTML 渲染器一样减少空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44028116/