Reputation: 940
Can you please tell me what will be the proper pattern for my requirement.
I have a string and I want find the string between particular pattern. I have code I tried so far but unable to get the expected result.
Input String
ssdfsfssXf1sddfsXfsdaf578ds0Xafds1dsfXdafspfsfsfsfds
Expected Result
Xf1sddfsX
Xafds1dsfX
Actual Result
Xf1sddfsXfsdaf578ds0Xafds1dsfX
VB Code
Sub RegEx_Tester()
Dim objRegExp As RegExp
Dim objMatch As Match
Dim colMatches As MatchCollection
Dim RetStr As String
' Create a regular expression object.
Set objRegExp = New RegExp
'Set the pattern by using the Pattern property.
objRegExp.Pattern = "X.*X"
' Set Case Insensitivity
objRegExp.IgnoreCase = True
'Set global applicability.
MyString = "ssdfsfssdXf1sddfsXfsdaf578ds0Xafds1dsfXdafspfsfsfsfds"
objRegExp.Global = True
Set colMatches = objRegExp.Execute(MyString) ' Execute search.
For Each objMatch In colMatches ' Iterate Matches collection.
Debug.Print objMatch.Value
Next
End Sub
Thanks In Advance !!
Upvotes: 0
Views: 65
Reputation: 46871
Use Non-greedy(Lazy) way
Change :
X.*X
To:
X.*?X
OR better use
X[^X]*+X
Negated Character Classes/Sets
Typing a caret after the opening square bracket negates the character class. The result is that the character class matches any character that is not in the character class.
Possessive quantifiers are a way to prevent the regex engine from trying all permutations. This is primarily useful for performance reasons.
A worth reading post on ✽ Want to Be Lazy? Think Twice.
However, a lazy quantifier has a cost: at each step inside the braces, the engine tries the lazy option first (match no character), then tries to match the next token (the closing brace), then has to backtrack.
See ✽ A Time for Greed, a Time for Laziness.
A reluctant (lazy) quantifier can make you feel safe in the knowing that you won't eat more characters than needed and overshoot your match
Upvotes: 5