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

高洛峰
Release: 2017-01-18 16:49:39
Original
2427 people have browsed it

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

    }
Copy after login

Instructions: Just remember 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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template