Java method to replace the carriage return line break in a string

  • 2020-04-01 01:27:18
  • OfStack

Replace with a regular expression:

Code snippet:

String documentTxt = EntityUtils. ToString (entity, "GBK"); // get data
DocumentTxt = documentTxt. ReplaceAll (" \ \ n \ \ r \ \ t] ", ""); // removes the carriage return line feed from the content area

String class replaceAll has regular replacement function. \t for TAB \n for newline \r for return


Java regular usage:

Example method:


public void parseTxt(String content){
        Pattern p = Pattern.compile(Config.articlePtn);
        Matcher matcher = p.matcher(content);
        while(matcher.find()){
            System.out.println(matcher.group(1));
        }

    }

Note: just remember the Pattern class, whose static method complie parses a regular expression to generate a Pattern object.

Then use the model to match the string, get a Matcher, and walk through all the matches using Matcher's find method.

Groups are groups in regular expressions, and () expressions. Group (0) is the original string, gourp(1) is the first group matched to... That is, the index of the matched group starts at 1.


Related articles: