简体   繁体   English

Java:在新行的开头匹配重复字符,并用相同数量的替代字符替换

[英]Java: matching repeating character at beginning of new line and replacing with same number of alternatives

I have a plain text file with a number of lines (new line character is \\n ) Some of these lines start with a varying number of sequential repeating whitespace characters \\\\s . 我有一个包含多行的纯文本文件(新行字符为\\n ),其中某些行以不同数量的顺序重复空白字符\\\\s I want to replace each \\\\s with   我想用 替换每个\\\\s . Example file: 示例文件:

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

transforms to: 转换为:

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

Any suggestions? 有什么建议么?

Thanks 谢谢

text = text.replaceAll("(?m)(?:^|\\G) ", " ");

^ in MULTILINE mode matches the beginning of a line. 多行模式下的^匹配行的开头。
\\G matches the spot where the previous match ended (or the beginning of the input if there is no previous match). \\G匹配上一个匹配结束的位置(如果没有上一个匹配,则匹配输入的开头)。

If you're processing one line at a time, you can shorten the regex to "\\\\G " . 如果一次要处理一行,则可以将正则表达式缩短为"\\\\G "

//try this: //尝试这个:

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("&nbsp;");
  }

  buffer.append(line.subString(index) + "\n"); 
  System.out.println(buffer.toString()); 
} 
reader.close();

//some more cleanup code here //一些更多的清理代码

String line;
StringBuilder buf = new StringBuilder();
int i;
for (i=0; i<line.length(); i++)
{
    if (line.charAt(i) == ' ')
        buf.append("&nbsp;");
    else
        break;
}
if (i < line.length()) buf.append(line.substr(i));
line = buf.toString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM