坚持了一个C#普通防爆pression [英] Stuck with a C# Regular Expression

查看:146
本文介绍了坚持了一个C#普通防爆pression的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的数据库字段中包含以下文本:

I have the following text contained within a field in my DB:

[quote:5a7b87febe="mr smith"]This is some text.

This is more text on another line.[/quote:5a7b87febe]

我想构造一个普通的前pression将任何实例转换就像上面,变成:

I am trying to construct a regular expression that will convert any instances like the above, into:

<div><h4>Posted by mr smith</h4>This is some text.

This is more text on another line.</div>

我已经把迄今的图案出现工作情况下,人们在密封文本没有线断裂,但在上面的例子中,其中有文本另一条线路上,图案不匹配

The pattern I have put together so far appears to work for instances where there is no line break in the enclosed text, but in the above example where there is text on another line, the pattern is not matched.

在C#code我至今是:

The C# code I have so far is:

var exp = new Regex(@"(\[quote)(:\w+=\"")(.*?)(\""\])(.*?)(\[\/quote)(:\w+\])");
var str = exp.Replace(str, "<div><h4>Posted by $3</h4>$5</div>");

我的垃圾定期防爆pressions所以我不知道该如何处理任何字符出现在打开和关闭报价标记之间。

I am rubbish at Regular Expressions so am unsure how to handle 'any' characters that appear between the opening and closing 'quote' tags.

在理想情况下,我也想前pression处理上面的例子,如果可能的嵌套的实例。

Ideally, I would also like the expression to handle nested instances of the above example if possible.

一个值得一提的另一件事是,在一系列字符遵循的报价:每一次标签是唯一的,并且引号内的名称也将有所不同。

One other thing worth mentioning is that the series of characters that follow the 'quote:' tags are unique every time, and the name within quotes will also vary.

推荐答案

您将需要使用的后向引用,以匹配在开始标记的唯一编号。像这样的东西应该为你工作:

You would need to use a Backreference to match the unique number in the opening tag. Something like this should work for you:

var regex = new Regex(@"\[(quote:[a-z0-9]+)(=""([^""]+)?"")?\](.*)\[/\1\]", RegexOptions.SingleLine);
var str = regex.Replace(str, "<div><h4>Posted by $3</h4>$4</div>");

该解决方案已经过测试,与你的输入,但不与嵌套引用。这将是一个有点麻烦。

This solution has been tested with your input, but not with nested quotes. This will be a bit trickier.

修改:选中该解决方案使用嵌套的报价后,它的工作。你只需要重复调​​用​​,直到没有更多的替代品制成。它第一次将匹配外报价并保持内部报价完好更换内。样品code这样做(未经测试):

EDIT: After checking this solution with nested quotes, it does work. You just need to call it repeatedly until no more replacements are made. The first time it will match the outer quote and leave the inner quote intact inside the replacement. Sample code for doing this (untested):

// Repeatedly call this replacement
string last;
do 
{
    last = str;
    str = regex.Replace(str, "<div><h4>Posted by $3</h4>$4</div>");
} while (last != str);

这篇关于坚持了一个C#普通防爆pression的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆