使用正则表达式查找和替换单词 [英] Find and replace words using Regex

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

问题描述



我试图从字符串中找到href标记.然后我尝试查找在href中是否匹配了特定的单词,并使用VB.Net Regex
进行了替换

Hi,

I am try to find href tags from string. Then i try to find is particular words is matched in href and replace using VB.Net Regex

Public arrString() As String = New String() {"-bigsmile-", "-sadsmile-", "-worried-", "-cool-", "-wink-", "-sleepy-", "-blush-", "-wondering-", "-talking-", "-angry-", "-smile-", "-calls-", "-yesicon-", "-noicon-"}

Dim inputString as string = "<a href=http://www.domain.com-bigsmile->http://www.domain.com-bigsmile-</a>"

'Note: -bigsmile- is in arrString(). My aim is to replace every words from arrString contains in inputString
'i want the result should be <a href=http://www.domain.com>http://www.domain.com-bigsmile-</a>
' -bigsmile- is removed from href

Dim new_inputString as string = DumpHRefs(inputString)

Function DumpHRefs(ByVal inputString As String) As String
    Dim HRefPattern As String = "href\s*=\s*(?:""(?<1>[^""]*)""|(?<1>\S+))"
    Dim m As Match = Regex.Match(inputString, HRefPattern, RegexOptions.IgnoreCase Or RegexOptions.Compiled)

    Do While m.Success
      'here i found http://www.domain.com-bigsmile- and i dont know how to replace / remove -bigsmile-
      Console.WriteLine("Found href {0} at {1}.", m.Groups(1), m.Groups(1).Index)
      m = m.NextMatch()
    Loop

    Return inputString 
End Function

推荐答案

正则表达式是聪明的野兽,Rexex的重载之一.替换使用匹配评估程序委托: http: //msdn.microsoft.com/en-us/library/cft8645c.aspx#Y0 [
Regexes are clever beasts, one opf the overloads for Rexex.Replace uses a match evaluator delegate: http://msdn.microsoft.com/en-us/library/cft8645c.aspx#Y0[^] which allows you to do further processing on the text matched by the Regex.
If you write your routine to compare the match text as supplied by the Match parameter text, you can replace only those strings you are interested in. The link has an example.


我认为这篇文章可能会有帮助.

查找并替换为正则表达式 [
I think this article could be of some help.

Find and Replace with Regular Expressions[^]


谢谢OriginalGriff,为我提供了正确的指导

我自己做过的

Thanks OriginalGriff, for guide me to right way

i have done it myself

Function DumpHRefs(ByVal inputString As String) As String
    Dim HRefPattern As String = "href\s*=\s*(?:""(?<1>[^""]*)""|(?<1>\S+))"
    Dim r3 As New Regex(HRefPattern, RegexOptions.IgnoreCase)
    inputString = r3.Replace(inputString, AddressOf smily_replace)

    Return inputString
  End Function

  Function smily_replace(ByVal newstr As Match) As String
    Dim x As String = newstr.ToString()

    For Each word In arrString
      If x.Contains(word) Then x = x.Replace(word, "")
    Next

    Return x
  End Function


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

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