Home >Java >javaTutorial >Java method to replace carriage returns and line feeds in strings

Java method to replace carriage returns and line feeds in strings

高洛峰
高洛峰Original
2017-01-22 11:11:452732browse

Use regular expressions to replace:

Code snippet:

String documentTxt = EntityUtils.toString(entity,"gbk");//Get data
documentTxt=documentTxt. replaceAll("[\\t\\n\\r]", "");//Remove carriage returns and line feeds in the content area

Explanation: The replaceAll of the String class has a regular replacement function. \t is tab character\n is line feed\r is carriage 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));
        }

    }

Instructions: Just remember the Pattern class, Its static method compile parses a regular expression to generate a Pattern object.

Then use the model to match the string, get a Matcher, and traverse all matches through the find method of the matcher.

group is the group in the regular expression, and () expression. group(0) is the original string, gourp(1) is the first matched group...that is, the index of the matched group starts from 1.

For more Java related articles on how to replace carriage returns and line feeds in strings, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn