multiple search/replacements in a single Regex.Replace?

  • Thread starter Thread starter Craig Buchanan
  • Start date Start date
C

Craig Buchanan

Is there a way to combine these two Replace into a single line?

Regex.Replace(Subject, "\&", "&")
Regex.Replace(Subject, "\'", "'")

Perhaps Regex.Replace(Subject, "{\&|\'}", "{&|'}")

Thanks,

Craig
 
Hi Craig

Depends what you want to do, however using the Regex for this cost you
probably 100 times more time than doing a normal *string* replace.

So doing 2 times with that string replace will save you a lot of time

Cor
 
Craig,
You can use a MatchEvaluator (a delegate) to call a routine for each match
you find, then you can simply call Regex.Replace with your pattern & the
AddressOf your routine. The routine will take the inner stuff found & return
the new value.

Something like:

Regex.Replace(Subject, "(\&|\"")", AddressOf Match_Craig)

Private Function Match_Craig(ByVal m As Match) As String
Select Case m.Groups[0].Value
case "&"
return "&"
case """"
return "'"
End Select
End Function

However I don't think I would use a RegEx in this case, I think I would use
StringBuilder.Replace in this case as you are replacing based on fixed
words, not on patterns. RegEx.Replace are better are replacing based on
patterns. ("\&" is a fixed pattern, unlike "9*" which is a variable
pattern).

Dim sb As New StringBuilder(Subject)
sb.Replace("&", "&")
sb.Replace("""", "'")
Subject = sb.ToString();


Remember there are three Split functions in .NET:

Use Microsoft.VisualBasic.Strings.Split if you need to split a string based
on a specific word (string). It is the Split function from VB6.

Use System.String.Split if you need to split a string based on a collection
of specific characters. Each individual character is its own delimiter.

Use System.Text.RegularExpressions.RegEx.Split to split based
on matching patterns.

Hope this helps
Jay
 
Back
Top