user864309
user864309

Reputation: 226

Java RegEx to replace a XML tag name

I am trying to replace the MessageParam within the XML tag with XXYY1...

The MessageParam has requested to travel <BR/>From <MessageParam name="0" desc="city code"/> to <MessageParam name="1" desc="city code"/> on <MessageParam name="2" desc="date"/> at <MessageParam name="3" desc="time"/>.

I expect the output to be

The MessageParam has requested to travel <BR/>From <XXYY1 name="0" desc="city code"/> to <XXYY2 name="1" desc="city code"/> on <XXYY3 name="2" desc="date"/> at <XXYY4 name="3" desc="time"/>.

Here is my code

private void ProcessString()
{
    String text = "The Traveler has requested to travel <BR/>From <MessageParam name=\"0\" desc=\"city code\"/> to <MessageParam name=\"1\" desc=\"city code\"/> on <MessageParam name=\"2\" desc=\"date\"/> at <MessageParam name=\"3\" desc=\"time\"/>.";
    int Counter = 0;
    StringBuffer outString = new StringBuffer();
    Pattern pattern = Pattern.compile("(<MessageParam.*?>)");
    Matcher matcher = pattern.matcher(text);

    while (matcher.find())
    {
        Counter++;
        String sReplacer = new StringBuffer("XXYY").append(Counter).toString();
        matcher.appendReplacement(outString, sReplacer);
    }
    matcher.appendTail(outString);
    System.out.println(outString.toString());
  }

The output i am getting is

 The MessageParam has requested to travel <BR/> From XXYY1 to XXYY2 on XXYY3 at XXYY4.

I am pretty sure that my regex is not correct. since i am not good with regex i am not able to figure out whats going wrong.

Upvotes: 2

Views: 1638

Answers (3)

prageeth
prageeth

Reputation: 7395

Simply use <MessageParam as the regex and use <XXYY as the replacement string portion.

Upvotes: 0

Anirudha
Anirudha

Reputation: 32787

The regex should be (?<=<)MessageParam

That would solve your problem

Upvotes: 2

duffymo
duffymo

Reputation: 308733

I wouldn't do such a thing with a regular expression.

I'd prefer to parse the source XML and map target values into an output XML using a template engine like Velocity.

My second choice would be an XSL-T transformation from one XML to another.

Upvotes: 3

Related Questions