How to use beginning and endline markers in regex for Java String?

后端 未结 5 2052
没有蜡笔的小新
没有蜡笔的小新 2021-01-04 19:51

Why doesn\'t the following change the text for me in Android?

String content = \"test\\n=test=\\ntest\";
content = content.replaceAll(\"^=(.+)=$\", \"

        
5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-04 20:35

    In Java String objects \n isn't considered a beginning of a line or an end of a line. It's a line feed. To match this, you need to change your code to

    String content = "test\n=test=\ntest";
    content = content.replaceAll("\n=(.+)=\n", "\n$1\n");
    

    What ^ and $ match, are the beginning and the end of the String object itself.

    If you're reading from a file, the newline could be a CRLF character in which case you want to match \r too. In that case you need to use a regex like this

    content = content.replaceAll("[\n\r]=(.+)=[\n\r]", "\n$1\n");
    

    If you need to match to work in multiple instances in multiple 'lines' in the same String, you should first split the String to multiple lines.

    String content = "test\n=test=\n=test=\ntest";
    String[] pieces = content.split("[\r\n]");
    StringBuilder replaced = new StringBuilder();
    
    for (int i=0; i$1");
        replaced.append(piece);
        replaced.append('\n');
    }
    

提交回复
热议问题