Link to home
Start Free TrialLog in
Avatar of Joakim_
Joakim_

asked on

Regular Expression Replace with Many Patterns

Is it possible to use the replace function and define the pattern in the function, so I can have many patterns with only one object, just like in this C++ code: http://www.developer.com/net/cplus/article.php/3495511

If so, how?
ASKER CERTIFIED SOLUTION
Avatar of snavebelac
snavebelac

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Joakim_
Joakim_

ASKER

That wasn't actually what I was looking for, snavebelac, but when I tried to do what you said, I came up with something else, thanks to you.

By the way, here's what I came up with - a handy function for using RegExp.Replace() function in the same way as Replace(), but this one with a RegExp pattern:

--------------------

Function FormatTextRegExpReplace(strFormatString, strFormatReplacePattern, strFormatReplaceOutput)

      ' Dimension variables.
      Dim objFormatTextOrdinaryRegExp                  ' Holds the "RegExp" object.

      ' Create a regular expression object.
      Set objFormatTextOrdinaryRegExp = New RegExp

      ' Set the regular expression pattern.
      objFormatTextOrdinaryRegExp.Pattern = strFormatReplacePattern

      ' Match all occurrences of the pattern.
      objFormatTextOrdinaryRegExp.Global = True

      ' Set the function value.
      FormatTextRegExpReplace = objFormatTextOrdinaryRegExp.Replace(strFormatString, strFormatReplaceOutput)

      ' Reset server objects.
      Set objFormatTextOrdinaryRegExp = Nothing

End Function

Function FormatText(strString)

      ' Dimension variables.
      Dim strResult                  ' Holds a randomly named variable. (I'll fix this comment later.)

      strResult = FormatTextRegExpReplace(strString, "<", "&lt;")
      strResult = FormatTextRegExpReplace(strResult, ">", "&gt;")
      strResult = FormatTextRegExpReplace(strResult, "T", "&gt;")
      FormatText = strResult

End Function

Response.Write(FormatText("This is a string with some <b>HTML tags</b> in it."))
Avatar of Joakim_

ASKER

That one replaces "T" with "&gt;", which it shouldn't - I did it just for testing.

Usage of the function: just add as many "strResult = FormatTextRegExpReplace()"s as you want. Put the RegExp pattern in the first quotes, and what it should be replaced with in the second quotes.

In example...

strResult = FormatTextRegExpReplace(strResult, "^;", "&nbsp;&nbsp;&nbsp;")

...Replaces lines starting with ";" indented with three spaces.