Elad Benda Elad Benda - 3 months ago 7
Java Question

how to use regex grouping to remove all instances for a pattern

I want to replace a request text with "_"

I thought to use java grouping regex syntax. But i got messed up.

here is my input:


Failed to handle request 0[null->null s:0 w:0.0 a: 0.0 S:0 t: 24543060
s(NA) (0 0)] on subject RealTimeUpdate


expected output:


Failed to handle request _ on subject RealTimeUpdate


part b

how can I remove all instances of this pattern in a text?

input:


Failed to handle request 0[null->null s:0 w:0.0 a: 0.0 S:0 t: 24543060
s(NA) (0 0)] on subject RealTimeUpdate. Request was: 0[null->null s:0
w:0.0 a: 0.0 S:0 t: 24543060 s(NA) (0 0)]


expected output:


Failed to handle request _ on subject RealTimeUpdate. Request was: _


here is my try:

Pattern p = Pattern.compile("(\"Failed to handle request\")(\\d)("[")(.*)(\"]\")(.*)");
Matcher m = p.matcher(input);
if (m.find()) {
String output = m.replaceAll("$1"+"$2"+"$3"+"_"+"$5"+"$6");
}


or

if I'm promised that the pattern starts with
"[null->null"
:

str.replaceAll((\\d)(\"[null->null\")(*.)(\"]\")", "X");

Answer

I don't now your request syntax exactly, but assuming it's comprised of a number followed by text in brackets, you could use str = str.replaceAll( "\\d\\[.*?\\]", "_");.