开发者

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. I want to replace each \\s with  . Example file:

This is a line with no white space at the beginning
  This is a line with 2 w开发者_运维知识库hitespace 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).

If you're processing one line at a time, you can shorten the regex to "\\G ".


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


//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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜