正则表达式用于仅用标签替换链接

时间:2009-02-13 07:41:45

标签: asp.net regex

我想通过使用正则表达式将链接转换为明确的文本。在绑定数据网格时,我有一个将(看起来:文本)转换为链接的函数。我的函数就在这里。

Private Function Convertlook(ByVal str As String) As String

        Dim look As String
        Dim pattern As String = "\(look: ([a-z0-9$&.öışçğü\s]+)\)"
        Dim regex As New Regex(pattern, RegexOptions.IgnoreCase)
        Dim htmlanc As New System.Web.UI.HtmlControls.HtmlAnchor()
        Dim postbackRef As String = Page.GetPostBackEventReference(htmlanc, "$1")
        htmlanc.HRef = postbackRef
       str = regex.Replace(str, "(look: <a href=""javascript:" & htmlanc.HRef & """><font color=""#CC0000"">$1</font></a> )")      
        look = str
        Return look 

end function

问题是我想编辑文本,我怎么能把它反转为(看:文本)?我应该再次使用正则表达式,它可以正确表达它吗?

3 个答案:

答案 0 :(得分:1)

看起来正则表达式可以简化为“尖括号”之间的任何内容

Dim regex As New Regex(".*>(.*)</font.*", RegexOptions.IgnoreCase)
str = regex.Replace(str, "(look: $1)")

答案 1 :(得分:0)

保留文本的转换版本和未转换版本(即在ViewState或ControlState中)是不是更容易?这样可以省去很多麻烦。如果您的原始文本包含类似'&lt; font'的字符串会发生什么?

我建议:不要去那里,不值得努力。跟踪来源。

答案 2 :(得分:0)

我在C#中更改了您的代码,这是您想要的:

string str = "(look: trialText)";
string look = string.Empty;
string pattern = @"\(look: ([a-z0-9$&.öışçğü\s]+)\)";
Regex regex = new Regex(pattern, RegexOptions.IgnoreCase);
System.Web.UI.HtmlControls.HtmlAnchor htmlanc = new System.Web.UI.HtmlControls.HtmlAnchor();
string postbackRef = Page.GetPostBackEventReference(htmlanc, "$1");
htmlanc.HRef = postbackRef;

// Here I capture the text inside the anchor :
Match matchedText = regex.Match(str);
string textInsideLink = regex.Replace(matchedText.Value, "$1"); // textInsideLink = "trialText"

str = regex.Replace(str, "(look: <a href=\"javascript:" + htmlanc.HRef + "\"><font color=\"#CC0000\">$1</font></a> )");

// I replace captured text with another text :
str = Regex.Replace(str, "(" + textInsideLink + ")", "anotherTextInsideLink"); 
// str = "(look: <a href=\"javascript:__doPostBack('','anotherTextInsideLink')\"><font color=\"#CC0000\">anotherTextInsideLink</font></a> )"