VBScript: InStr with Regular Expression function

I don’t think there’s a built-in way to do an InStr with a regular expression as the search string in VBScript, so I wrote one:

Function inStrRegExp(sString, sPattern, bIgnoreCase)
  Dim oRegExp,aMatches, item, bFound, iPosition
  Set oRegExp = New RegExp
  oRegExp.IgnoreCase = bIgnoreCase
  oRegExp.Global = True
  oRegExp.Pattern = sPattern
  Set aMatches = oRegExp.Execute(sString)
  bFound = False

  For Each item In aMatches
    iPosition = item.FirstIndex
    bFound = True
    Exit For
  Next

  If bFound Then
    inStrRegExp = iPosition
  Else
    inStrRegExp = "-1"
  End If
End Function

Pass it the following:

sString = text string to search within
sPattern = standard VB Script RegExp pattern string
bIgnoreCase = set to True or False to make it use case insensitive or case sensitive matching

It returns the position of the first match within sString, or -1 if there is no match.

This entry was posted in Scripting and tagged , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s