Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace substring of matched regex

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
}
like image 240
Flexo Avatar asked May 26 '11 19:05

Flexo


People also ask

How do you replace a section of a string in regex?

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.

How do I replace only part of a match with Python re sub?

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.

Can I use regex in replace?

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.


2 Answers

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.

like image 184
Kaj Avatar answered Sep 20 '22 17:09

Kaj


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() + ']');

OUTPUT

Final: [2 dl. flour 4 cups of sugar]
like image 40
anubhava Avatar answered Sep 18 '22 17:09

anubhava