Mani kv
Mani kv

Reputation: 163

Vbscript Regular expression, find all between 2 known strings

I would like to select all texts between two know strings. Say for example the following text

*starthere
*General Settings 
*  some text1
*  some text2
*endhere

I would like to select all texts between "*starthere" and "*endhere" using vbscript. so that the final output looks like the following

 *General Settings 
    *  some text1
    *  some text2

I know this would be simpler using a regex since there are multiple instances of such pattern in the file i read.

I tried something like the following

/(.*starthere\s+)(.*)(\s+*endhere.*)/
/(*starthere)(?:[^])*?(*endhere)/

But they dont seem to work and it selects even the start and end strings together. Lookforward and backword dont seem to work either and iam not sure if they have support for vbscript.

This is the code I am using:

'Create a regular expression object 
Dim objRegExp
Set objRegExp = New RegExp 'Set our pattern
objRegExp.Pattern = "/\*starthere\s+([\s\S]*?)\s+\*endhere\b/" objRegExp.IgnoreCase = True
objRegExp.Global = True 
Do Until objFile.AtEndOfStream 
 strSearchString = objFile.ReadLine
 Dim objMatches
 Set objMatches = objRegExp.Execute(strSearchString)
 If objMatches.Count > 0 Then
  out = out & objMatches(0) &vbCrLf
  WScript.Echo "found"
 End If
Loop
WScript.Echo out
objFile.Close

Upvotes: 1

Views: 1667

Answers (1)

anubhava
anubhava

Reputation: 786241

You can use:

/\bstarthere\s+([\s\S]*?)\s+endhere\b/

and grab the captured group #1

([\s\S]*?) will match any text between these 2 tags including newlines.

Upvotes: 2

Related Questions