I fetch some html and do some string manipulation and en up with a string like
string sample = "\n \n 2 \n \n \ndl. \n \n \n flour\n\n \n 4 \n \n cups of \n\nsugar\n"
I would like to find all ingredient lines and remove whitespaces and linebreaks
2 dl. flour and 4 cups of sugar
My approach so far is to the following.
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
}
The \[[^\]]*]\[ matches [ , then any 0+ chars other than ] and then ][ . The (...) forms a capturing group #1, it will remember the value that you will be able to get into the replacement with $1 backreference. [^\]]* matches 0+ chars other than ] and this will be replaced.
Put a capture group around the part that you want to preserve, and then include a reference to that capture group within your replacement text. @Amber: I infer from your answer that unlike str. replace(), we can't use variables a) in raw strings; or b) as an argument to re. sub; or c) both.
How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.
sample = sample.replaceAll("[\\n ]+", " ").trim();
Output:
2 dl. flour 4 cups of sugar
With no spaces in the beginning, and no spaces at the end.
It first replaces all spaces and newlines with a single space, and then trims of the extra space from the begging / end.
Following code should work for 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() + ']');
Final: [2 dl. flour 4 cups of sugar]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With