Tim Falony Tim Falony - 3 months ago 20
Java Question

Uncomment an XML element through regex in Java

My XML looks like below,

<!-- Service Defs -->

<!-- <serviceName = "${NASA_Freedom.level.mission}"
MaxTimeOut = "20" minSpareHyperThread = "10" />
-->


And I just need to uncomment the serviceName element:

<serviceName = "${NASA_Freedom.level.mission}"
MaxTimeOut = "20" minSpareHyperThread = "10" />


The following code doesn't seem to do the trick:

Pattern p = Pattern.compile("(<!--).*<serviceName = \\"${NASA_Freedom.*(-->)");
Matcher m = p.matcher(test);
if (m.find()) {
System.out.println(m.replaceAll(""));
}


This also seems like a bad way to handle this. Unfortunately I cannot do anything about the XML file so this seems to be the only way. How do I un comment like above?

sln sln
Answer

This is one way

Find: "<!--(?:(?!-->)[\\S\\s])*?(<serviceName\\s+(?:(?:(?:\"[\\S\\s]*?\")|(?:'[\\S\\s]*?'))|(?:[^>]*?))+\\s*/>)[\\S\\s]*?-->"

Replace: "$1" (basically replacing group 0 with group 1 in the string)

Expanded:

 <!-- 
 (?:
      (?! --> )
      [\S\s] 
 )*?

 (                             # (1 start)
      <serviceName \s+ 
      (?:
           (?:
                (?: " [\S\s]*? " )
             |  (?: ' [\S\s]*? ' )
           )
        |  (?: [^>]*? )
      )+
      \s* />
 )                             # (1 end)

 [\S\s]*? -->

Input:

<!-- Service Defs -->

<!-- <serviceName = "${NASA_Freedom.level.mission}"
                 MaxTimeOut = "20" minSpareHyperThread = "10" />
-->

Output:

 **  Grp 0 -  ( pos 25 , len 122 ) 
<!-- <serviceName = "${NASA_Freedom.level.mission}"
                 MaxTimeOut = "20" minSpareHyperThread = "10" />
-->  
 **  Grp 1 -  ( pos 30 , len 112 ) 
<serviceName = "${NASA_Freedom.level.mission}"
                 MaxTimeOut = "20" minSpareHyperThread = "10" />