开发者

using Regular Expressions and tags to extract portion of text

So I开发者_如何学Go have a text file that is having special tags like:

{A1}
Text 1
{A1}

{A2}
Text 2
{A2}

How can I extract from the text using reg-ex the portion Text 2 or Text 1 ..? So I what to be able to extract only what is between tags A1 or only what is between Tags A2 .. not all of them ... at once! thanks!


In C# you can do something like this:


string output = Regex.Replace(YOUR_TEXT, @"\{(?<Tag>\w+).*?\}(?<text>\w+).*?\{\k<Tag>\}", "$2");

Nested tags are not suppoerted.


You can do it with the following regular expression if you assume that the document is well-formed and that your tags are not nested:

@"({.*?})(.*)\1"

Example:

Regex regex = new Regex(@"({.*?})(.*?)\1", RegexOptions.Singleline);
foreach (Match match in regex.Matches(s)) {
    Console.WriteLine(match.Groups[2].Value.Trim());
}

Output:

Text 1
Text 2
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜