简体   繁体   中英

Regular expression in java to replace string as mentioned below

<#if ${x} == 'abc' > ${add} <#else if ${y} == 'dfg' > bef </#if>

Here I want to remove all ${ and } which are inside < and > . , how can I do it in java? expected output should be

 <#if x == 'abc' > ${add} <#else if y == 'dfg' > bef </#if>

You can try this:

String str = "<#if ${x} == 'abc' > ${add} <#else if ${y} == 'dfg' > bef </#if>";
System.out.println(str.replaceAll("(<#.+?)\\$\\{(.+?)\\}(.+?>)", "$1$2$3"));     

Yields:

<#if x == 'abc' > ${add} <#else if y == 'dfg' > bef </#if>       

Regex Explanation available here .

EDIT: I have made some more amendments and also how I assume the else would be implemented. The code should do the trick:

String str = "<#if ${x} || ${z} > ${add} <#else if ${y} == 'dfg' && ${x} == 'abx'> bef <#else if ${y} == 'dfg' > sdadas <#else> ${foo}</#if>";
System.out.println(str.replaceAll("(?<=(?!<#else>)<#|\\|\\||&&)(.+?)\\$\\{(.+?)\\}", "$1$2"));  

Given this:

<#if ${x} || ${z} > ${add} <#else if ${y} == 'dfg' && ${x} == 'abx'> bef <#else if ${y} == 'dfg' > sdadas <#else> ${foo}</#if>

Yields:

<#if x || z > ${add} <#else if y == 'dfg' && x == 'abx'> bef <#else if y == 'dfg' > sdadas <#else> ${foo}</#if>

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