2

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.

2
  • You can search just for <MessageParam since you don't need the rest. Commented Jan 6, 2013 at 19:15
  • don't parse non-regular languages with a regular expression! Commented Jan 6, 2013 at 20:01

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

The regex should be (?<=<)MessageParam

That would solve your problem

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.