0

the question sounds a bit confusing, but it is actually straightforward. This is a follow-up of my previous post:

Need a little help on this regular expression

after successful transformation of the String, now the String looks like:

<media id="pc011018" rights="licensed"
        type="photo">
        <title>Sri Lankans harvest tea</title>

Now the only task left is to swap the three attributes of media node, so the output String should be:

<media type="photo" id="pc011018" rights="licensed">
        <title>Sri Lankans harvest tea</title>

I actually could think of a way of doing this: first of all, I extract the string enclosed by the first pair of "[" bracket. Then for this string, I will use a StringTokenizer to tokenize three attributes strings: type, id, rights; then rearrange them in a StringBuffer,turn it back into a string, then finally concatenate with the remaining [title] substring.

I am just wondering if there is a better and more efficient way rather than using StringToknizer? Please kindly help, thanks.

Community
  • 1
  • 1
Kevin
  • 6,711
  • 16
  • 60
  • 107
  • If you want to show literal text, indent it 4 spaces or use the 101010 button in the editor. I fixed it for you. – Jim Garrison Dec 15 '10 at 22:00
  • 4
    If this is XML, then the order of the attributes shouldn't matter to any downstream XML processor. Why do you need them to be in a certain order? Also, it sounds like you really need to be using XSLT instead of regexes to do this. – Jim Garrison Dec 15 '10 at 22:01

1 Answers1

2

A real hacky way of doing this

    String input="<media id=\"pc011018\" rights=\"licensed\" type=\"photo\"><title>Sri Lankans harvest tea</title></media>";
    Pattern r= Pattern.compile("<media id=\"(.*)\" rights=\"(.*)\" type=\"(.*)\">(.*)");
    Matcher m = r.matcher(input);
    m.find();
    System.out.println("<media type=\""+m.group(3)+ "\" + id=\""+ m.group(1) + "\" rights=\"" + m.group(2) + "\">"+m.group(4));

Will only work if the data is always as you describe

Samuel Parsonage
  • 3,077
  • 1
  • 18
  • 21