替换为正则表达式 [英] Replace with regex

查看:101
本文介绍了替换为正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨!



我正在尝试使用正则表达式替换一些文本。我不确定它的相关性,但文本来自vb.net中的Treeview控件。我使用以下基本正则表达式:< creationDate>(。*?)< / creationDate>哪个很棒!



这里是子:



Dim nNode As TreeNode

Dim sPattern As String ="<" &安培; sTag& "><(*); /" &安培; sTag& ">"

Dim rx As New Regex(sPattern)

Dim m As Match





每个nNode在nParent.Nodes中

m = rx.Match(nNode.Text)

如果m.Success = True那么

rx。替换(nNode.Text,sPattern,sText)

退出Sub

结束如果

下一个





所以正则表达式找到我正在寻找的模式。但替换不起作用。我注意到rx.Replace函数返回一个字符串。当我从rx.Replace返回一个值时 - 它只是sText值。我希望能够保留标签值。我知道我可以使用蛮力方法解决这个问题,但我希望使用正则表达式的优雅。

谢谢!






解决方案

你可以做的就是将sPattern字符串修改为:Dim sPattern As String ="(<"& sTag&" ;>)(。*?)(< /"& sTag&">)"
从那里你可以像这样修改sText值:"


1" + sText +"


3"

有关此方法的更多信息,请访问: http://www.javascriptkit.com/javatutors/re3.shtml 结果

Hi!

I am trying to replace a bit of text using a regex.  Im not sure its relevant but the text is from a Treeview control in vb.net.  I am using the following basic regex: <creationDate>(.*?)</creationDate> which works great!

here is the sub:

Dim nNode As TreeNode
        Dim sPattern As String = "<" & sTag & ">(.*?)</" & sTag & ">"
        Dim rx As New Regex(sPattern)
        Dim m As Match


        For Each nNode In nParent.Nodes
            m = rx.Match(nNode.Text)
            If m.Success = True Then
                rx.Replace(nNode.Text, sPattern, sText)
                Exit Sub
            End If
        Next


So the regex works as far as finding the pattern Im looking for.  But the replace isn't working.  I noticed that the rx.Replace function returns a string.  When I return a value from the rx.Replace -  its the sText value only.  I want to be able to keep the tag values.  I know I can solve this using a brute force method, but I was hoping to use the regex elegance.

thanks!




解决方案

On thing you could do is modify the sPattern string to: Dim sPattern As String = "(<" & sTag & ">)(.*?)(</" & sTag & ">)"
From there you can  modify the sText value like so: "


1"+sText+"


3"

More information on this method can be found here: http://www.javascriptkit.com/javatutors/re3.shtml


这篇关于替换为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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