获取所有出现的子串匹配模式

时间:2012-06-27 08:06:56

标签: c# regex

我有一个字符串在这个表格上:

"Some text [asd](fgh) Lorem Ipsum [qwert](y)" 

您可能会将此识别为降价语法。

我想用这样的链接替换模式的所有出现:

<a href="fgh">asd</a>

最好的方法是什么?我可以毫无问题地进行实际替换,但我不确定如何识别子串。我怀疑正则表达式是要走的路?

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

是的,我认为正则表达式在这里可以:

resultString = Regex.Replace(subjectString, 
    @"\[     # Match [
    (        # Match and capture in group 1:
     [^][]*  #  Any number of characters except brackets
    )        # End of capturing group 1
    \]       # Match ]
    \(       # Match (
    (        # Match and capture in group 2:
     [^()]*  #  Any number of characters except parentheses
    )        # End of capturing group 2
    \)       # Match )", 
    "<a href=\"$2\">$1</a>", RegexOptions.IgnorePatternWhitespace);
相关问题