views:

128

answers:

2

Hi!

i need to replace an undefined tags inside an xml string.

example: <abc> <>sdfsd <dfsdf></abc><def><movie></def> (only <abc> and <def> are defined)

should result with: <abc> &lt;&gt;sdfsd &lt;dfsdf&gt;</abc><def>&lt;movie&gt;<def> <> and <dfsdf> are not predefined as and and does not have a closing tag.

it must be done with a regex!. no using xml load and such.

i'm working with C# .Net

Thanks!

+1  A: 

it must be done with a regex! no using xml load and such.

I must hammer this nail in with my boot! No using a hammer and such. It's an old story :)

You'll need to supply more information. Are "valid" tags allowed to be nested? Are the "valid" tags likely to change at any point? How robust does this need to be?

Assuming that your list of valid tags isn't going to change at any point, you could do it with a regex substitution:

s/<(?!\/?(your|valid|tags))([^>]*)>/&lt;$1&gt;/g
Anon.
While this looks like it will work fine according to the requirements he gave, unfortunately I suspect it's not what he wants because if you read his other question he wrote a comment: `this is my actual example, which will solve all the cases. "<abc>>sdfsdf<<asdada>>asdasd<>asdasd<asdsad>asds<</abc>"` and I guess your answer will fail for this example (haven't tested it though).
Mark Byers
+2  A: 

How about this:

    string s = "<abc> <>sdfsd <dfsdf></abc><def><movie></def>";
    string regex = "<(?!/?(?:abc|def)>)|(?<!</?(?:abc|def))>";
    string result = Regex.Replace(s, regex, match =>
    {
        if (match.Value == "<")
            return "&lt;";
        else
            return "&gt;";
    });
    Console.WriteLine(result);

Result:

<abc> &lt;&gt;sdfsd &lt;dfsdf&gt;</abc><def>&lt;movie&gt;</def>

Also, when tested on your other test case (which by the way I found in a comment on the other question):

<abc>>sdfsdf<<asdada>>asdasd<>asdasd<asdsad>asds<</abc>

I get this result:

<abc>&gt;sdfsdf&lt;&lt;asdada&gt;&gt;asdasd&lt;&gt;asdasd&lt;asdsad&gt;asds&lt;</abc>

Let me guess... this doesn't work for you because you just thought of a new requirement? ;)

Mark Byers
+1 for the last line
Jay
thanks! thanks !
Jack
no....no new requierments. i'm so sorry for the bothering :) won't do it next time :)
Jack
@Jack: Well you got what you wanted, that's the important thing. Just remember that the sort of answers you get depend on the quality of the question, so if you spend a bit longer making the question more precise you probably won't have to wait so long to get an answer you can use. We don't need several pages of details, but there are a few key details that you really need to give, because without those details we don't have a chance of getting the answer right. There was not enough information in this question to produce this answer - I only got it because I read your other question too.
Mark Byers