title: RegEx to replace namespace in XML
body: <p>I need to replace namespace with some value</p>
  
  <pre><code>     private static String REGEX1 = "(&lt;\\/?)[ns2]+?:";
  
      private static String INPUT = "&lt;ns1:fso xmlns:ns2='https://www.example.com/fsoCanonical'&gt;&lt;ns2:senderId xmlns='http://www.example.com/fsoCanonical'&gt;abc&lt;/ns2:senderId&gt;&lt;receiverId xmlns='http://www.example.com/fsoCanonical'&gt;testdata&lt;/receiverId&gt;   &lt;messageId xmlns='http://www.example.com/fsoCanonical'&gt;4CF4DC05126A0077E10080000A66C871&lt;/messageId&gt;    &lt;/ns1:fso&gt; ";
      private static String REPLACE = "$1cc:";
  
      public static void main(String[] args) {
                  Pattern p = Pattern.compile(REGEX1);
                  Matcher m = p.matcher(INPUT); // get a matcher object
                  StringBuffer sb = new StringBuffer();
                  while (m.find()) {
                   m.appendReplacement(sb, REPLACE);
                 }
                  m.appendTail(sb);
                System.out.println(sb.toString());
  </code></pre>
  
  <p>I need to replace my namespace from ns2 to cc but the above code can replace only the ns2: to cc: and I need to replace the tag with xmlns:ns2=  with xmlns:cc= also. Please advise how to replace this using the same regex condition.</p>
  
  <pre><code>         &lt;ns1:fso xmlns:ns2='https://www.example.com/fsoCanonical'&gt;&lt;ns2:senderId xmlns='http://www.example.com/fsoCanonical'&gt;abc&lt;/ns2:senderId&gt;&lt;receiverId xmlns='http://www.example.com/fsoCanonical'&gt;testdata&lt;/receiverId&gt;   &lt;messageId xmlns='http://www.example.com/fsoCanonical'&gt;4CF4DC05126A0077E10080000A66C871&lt;/messageId&gt;    &lt;/ns1:fso&gt; "
  </code></pre>
  
  <p>to </p>
  
  <pre><code>      &lt;ns1:fso xmlns:cc='https://www.example.com/fsoCanonical'&gt;&lt;cc:senderId xmlns='http://www.example.com/fsoCanonical'&gt;abc&lt;/cc:senderId&gt;&lt;receiverId xmlns='http://www.example.com/fsoCanonical'&gt;testdata&lt;/receiverId&gt;   &lt;messageId xmlns='http://www.example.com/fsoCanonical'&gt;4CF4DC05126A0077E10080000A66C871&lt;/messageId&gt;    &lt;/ns1:fso&gt; "
  </code></pre>