Debugging Regular Expressions

dhancy

Board Regular
Joined
Jul 10, 2013
Messages
120
Office Version
  1. 2016
Platform
  1. Windows
I have this code:

VBA Code:
Dim r As RegExp
Dim s As String

Set r = New RegExp

s = "(code IN ('C', 'E', 'F') AND (other stuff))"

r.Pattern = "IN \(.+\)"
r.Global = False

Set theMatches = r.Execute(s)

For Each Match In theMatches
    MsgBox Match.Value
Next

My goal is to extract the string that starts with the word IN and ends with a right parenthesis.


When I run this, the result is: IN ('C', 'E', 'F') AND (other stuff))


How come it doesn't stop after the first ) ?


(As a secondary question, since I only want the first occurrence of this, is there any way to code the last bit so I don't need a for loop?)

Thanks!


Dennis
 

Excel Facts

Excel Joke
Why can't spreadsheets drive cars? They crash too often!
Dennis

Try this for the pattern.
VBA Code:
r.Pattern = "IN \(.*?\)"
 
Upvote 0
Thanks! It works!

Just after I posted this, i tried this pattern, and it worked too.

VBA Code:
r.Pattern = "IN \([^)]+\)"
 
Upvote 0
My goal is to extract the string that starts with the word IN and ends with a right parenthesis.
Then this lesser pattern should also do the job?
VBA Code:
r.Pattern = "IN.*?\)"


(As a secondary question, since I only want the first occurrence of this, is there any way to code the last bit so I don't need a for loop?)
You have already set Global = False so you will only get at most 1 match (the first one). Therefore, instead of that loop ..

VBA Code:
MsgBox theMatches(0)
 
Upvote 0
That's awesome. Thanks!!

When I started researching this, the only example I saw was that "for" loop. For my situation, your solution is perfect.
 
Upvote 0
You're welcome. Thanks for the follow-up. :)
 
Upvote 0

Forum statistics

Threads
1,213,489
Messages
6,113,949
Members
448,534
Latest member
benefuexx

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top