Java – replace substrings of matching regular expressions
•
Java
I get some HTML and do some string manipulation and use similar strings
string sample = "\n \n 2 \n \n \ndl. \n \n \n flour\n\n \n 4 \n \n cups of \n\nsugar\n"
I want to find all component lines and remove spaces and line breaks
2 dl. Flour and 4 cups sugar
So far, my method is as follows
Pattern p = Pattern.compile("[\\d]+[\\s\\w\\.]+"); Matcher m = p.matcher(Result); while(m.find()) { // This is where i need help to remove those pesky whitespaces }
Solution
The following code should suit you:
String sample = "\n \n 2 \n \n \ndl. \n \n \n flour\n\n \n 4 \n \n cups of \n\nsugar\n"; Pattern p = Pattern.compile("(\\s+)"); Matcher m = p.matcher(sample); sb = new StringBuffer(); while(m.find()) m.appendReplacement(sb," "); m.appendTail(sb); System.out.println("Final: [" + sb.toString().trim() + ']');
OUTPUT
Final: [2 dl. flour 4 cups of sugar]
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码