Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我想使用正则表达式拆分字符串,就像在这个例子中一样,但在我的情况下,我希望新行中的每个单词都不会超过 X 个字符。
所以下面的代码不能解决问题,因为它找到了至少 X 个非换行符(而不是最大 X)的每个实例。
s = s.replaceAll("(.{" + x + ",}?)\\s+", "$1\n");
我可以使用其他方法轻松做到这一点,但我想使用 REGEX
试试这个:
s = s.replaceAll("(.{0,"+ x+"})\\b", "$1\n");
或修剪版,
s = s.replaceAll("(?:\\s*)(.{1,"+ x +"})(?:\\s+|\\s*$)", "$1\n")