Java:匹配新行开头的重复字符,并替换为相同数量的替代字符
我有一个有许多行的纯文本文件(新行字符是Java:匹配新行开头的重复字符,并替换为相同数量的替代字符,java,regex,whitespace,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 转换为: This is a
\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
转换为:
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
有什么建议吗
谢谢//试试这个:
BufferedReader reader = new BufferedReader(new FileReader("filename"));
String line;
StringBuffer buffer;
while ((line = reader.readLine()) != null) {
buffer = new StringBuffer();
int index = line.indexOf(line.trim());
for (int i = 0; i < index; i++) {
buffer.append(" ");
}
buffer.append(line.subString(index) + "\n");
System.out.println(buffer.toString());
}
reader.close();
BufferedReader reader=new BufferedReader(new FileReader(“filename”);
弦线;
字符串缓冲区;
而((line=reader.readLine())!=null){
buffer=新的StringBuffer();
int index=line.indexOf(line.trim());
对于(int i=0;i
//这里还有一些清理代码字符串行;
String line;
StringBuilder buf = new StringBuilder();
int i;
for (i=0; i<line.length(); i++)
{
if (line.charAt(i) == ' ')
buf.append(" ");
else
break;
}
if (i < line.length()) buf.append(line.substr(i));
line = buf.toString();
StringBuilder buf=新的StringBuilder();
int i;
对于(i=0;i
多行模式下的^
匹配行的开头。
\G
匹配上一个匹配结束的位置(如果没有上一个匹配,则匹配输入的开始)
如果一次处理一行,可以将正则表达式缩短为“\\G”
您将在原始输入中丢失尾随空格,因为到目前为止,两个答案都没有使用正则表达式,这是我的原始方法。谢谢。将Alan Moore基于正则表达式的解决方案与我的简单方法进行基准测试会很有趣。我不会在一百万年内得到它,谢谢。\\G
text = text.replaceAll("(?m)(?:^|\\G) ", " ");