C#Regex.Replace():获取值 [英] C# Regex.Replace(): getting the values
问题描述
我解析一个BB代码图像标签:
I'm parsing a BB code image tag:
[IMG] http://imagesource.com [/ IMG]
[img]http://imagesource.com[/img]
我用下面的替换()函数:
I'm using the following Replace() function:
Regex.Replace(msg, @"\[img\]([^\]]+)\[\/img\]", @"<img src=""$1"" border=""0"" />", RegexOptions.IgnoreCase);
和我需要的URL在解析。我需要知道的$ 1的值。是否可以?正则表达式类某种程度上取代了$ 1的字符串,我需要的价值,所以必须有一种方式来获得它。
And I need to get the URL while parsing. I need to know the value of "$1". Is it possible? The Regex class somehow replaces the "$1" string with the value that I need, so there must a way to get it.
推荐答案
这听起来像你正在寻找的替换
方法与接受MatchEvaluator过载。该方法的MSDN页面可以在这里找到 。
It sounds like you're looking for the Replace
method with an overload that accepts a MatchEvaluator. The MSDN page for that method can be found here.
试试这个:
string input = "[img]http://imagesource.com[/img]";
string pattern = @"\[img]([^\]]+)\[\/img]";
string result = Regex.Replace(input, pattern, m =>
{
var url = m.Groups[1].Value;
// do something with url here
// return the replace value
return @"<img src=""" + url + @""" border=""0"" />";
},
RegexOptions.IgnoreCase);
这使用多语句的lambda简化与组工作,并进行更多的逻辑返回更换之前值。你当然可以,逃脱这个代替:
This uses a multi-statement lambda to simplify working with the group and performing more logic before returning the replacement value. You could, of course, get away with this instead:
string result = Regex.Replace(input, pattern,
m => @"<img src=""" + m.Groups[1].Value + @""" border=""0"" />",
RegexOptions.IgnoreCase);
在上述情况下,没有必要为收益
但它只是返回,无需额外的评估原始字符串。你可以沾些三元运营商,并添加逻辑,但它会显得凌乱。多语句的lambda干净多了。可以考虑打破它在其自己的方法,如图前述MSDN链接,如果是过大或将在其他 Regex.Replace
努力被重用。
In the above case there's no need for the return
but it's just returning the original string without additional evaluation. You could stick some ternary operators and add that logic, but it'll look messy. A multi-statement lambda is much cleaner. You may consider breaking it out in its own method, as shown in the aforementioned MSDN link, if it is too large or will be reused in other Regex.Replace
efforts.
顺便说一句,我还通过删除转义为]
。开场仅 [
需要转义。
BTW, I also simplified your pattern slightly by removing the escapes for ]
. Only the opening [
needs to be escaped.
这篇关于C#Regex.Replace():获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!