Ric*_*d H 0 java regex whitespace
我有一个带有多行的纯文本文件(新行字符是\n)这些行中的一些以不同数量的连续重复空白字符开头\\s.我想替换每个\\s用 .示例文件:
This is a line with no white space at the beginning
This is a line with 2 whitespace characters at the beginning
This is a line with 4 whitespace at the beginning
Run Code Online (Sandbox Code Playgroud)
转换为:
This is a line with no white space at the beginning
This is a line with two whitespace characters at the beginning
This is a line with 4 whitespace at the beginning
Run Code Online (Sandbox Code Playgroud)
有什么建议?
谢谢
text = text.replaceAll("(?m)(?:^|\\G) ", " ");
Run Code Online (Sandbox Code Playgroud)
^在MULTILINE模式下匹配一行的开头.
\G匹配上一个匹配结束的位置(如果没有先前的匹配,则匹配输入的开头).
如果您一次处理一行,则可以将正则表达式缩短为"\\G ".