简体   繁体   中英

Java Regex to replace Substring

String expression = "${abcd?string(datePattern)}\" href=\"\">From Date</a>&nbsp;-&nbsp;${dasfsaf?string(datePattern)}\" href=\"\">To Date</a>";
expression=expression.replaceAll("(})(\".+</a>)(.+?)", "$1$3");
System.out.println(expression);

The output that is coming is :

${abcd?string(datePattern)}&nbsp;-&nbsp;${dasfsaf?string(datePattern)}" href="">To Date</a>

The expected Output is :

${abcd?string(datePattern)}&nbsp;-&nbsp;${dasfsafT?string(datePattern)}

The problem is it is only replacing the content between the first { and </a> and not the ones after that. I want all content to be replaced between these two..

in your regex you require there to be something after the </a> as you have (.+?) you can change that to (.*?) and it should work as you are no longer requiring there to be anything afterwards and your second part can match (alternatively, it doesn't appear to have any role so I would just delete it). In addition you probably don't want the greedy quantifier in the middle .+ so change that to lazy .+?

expression=expression.replaceAll("(})(\".+?</a>)", "$1");

Not the exact regex answer but you can simply repeat the replaceAll call. That's what i do when i don't have time and if it won't be costly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM