代码之家  ›  专栏  ›  技术社区  ›  Richard H

Java:在新行开始处匹配重复字符并替换为相同数量的替代字符

  •  0
  • Richard H  · 技术社区  · 14 年前

    我有一个包含许多行的纯文本文件(新行字符是 \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
    

    有什么建议吗?

    谢谢

    3 回复  |  直到 14 年前
        1
  •  5
  •   Alan Moore Chris Ballance    14 年前
    text = text.replaceAll("(?m)(?:^|\\G) ", " ");
    

    ^ 在多行模式下,匹配行首。
    \G

    如果一次处理一行,可以将regex缩短为 "\\G " .

        2
  •  1
  •   Jim Garrison    14 年前
    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();
    
        3
  •  1
  •   user500074 user500074    14 年前

    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();
    

    //这里还有一些清理代码