Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am given a string that has place holders in the format of {{some_text}}. I would like to extract this into a collection using C# and believe RegEx is the best way to do this. RegEx is a little over my head but it seems powerful enough to work in this case. Here is my example:

<a title="{{element='title'}}" href="{{url}}">
<img border="0" alt="{{element='title'}}" src="{{element='photo' property='src' maxwidth='135'}}" width="135" height="135" /></a>
<span>{{element='h1'}}</span>
<span><strong>{{element='price'}}<br /></strong></span>

I would like to end up with something like this:

collection[0] = "element='title'";

collection[1] = "url";

collection[2] = "element='photo' property='src' maxwidth='135'";

collection[3] = "element='h1'";

collection[4] = "element='price'";

Notice that there are no duplicates either, but I do not want to complicate things if it is difficult to do.

I saw this post that does something similar but within brackets: How to extract the contents of square brackets in a string of text in c# using Regex

My problem here is that I have double braces instead of just one character. How can I do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
522 views
Welcome To Ask or Share your Answers For Others

1 Answer

Taking exactly from the question you linked:

ICollection<string> matches =
    Regex.Matches(s.Replace(Environment.NewLine, ""), @"{{([^}]*)}}")
        .Cast<Match>()
        .Select(x => x.Groups[1].Value)
        .ToList();

foreach (string match in matches)
    Console.WriteLine(match);

I've changed the [ and ] to {{ and }} (escaped). This should make the collection you need. Be sure to read the first answer to the other question for the regex breakdown. It's important to understand it if you use it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...