Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
505 views
in Technique[技术] by (71.8m points)

c# - Extract string between braces using RegEx, ie {{content}}

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...