Home » excel » Is there a way to make this Regex expression less greedy. Using Excel VBA

Is there a way to make this Regex expression less greedy. Using Excel VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an excel document with a cell with the following information:

A) Current to: Notice of 19 June 2014  Sent on: August 2012
B) Updated on: October 2018
C) Updated: 14 January 2009

I am using the following regular expression with some success:

(\b\d{1,2}\D{0,3})?\b((?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(?:Nov|Dec)(?:ember)?))\D?(\d{1,2}\D?)?\D?((19[7-9]\d|20\d{2})|\d{2})

the output I have is as follows:

A) 19 June2014August2012
B) October 2018
C) 14 January 2009

B and C extract fine, however I am expecting 19 June 2014 for A

I have tried adding .*? to make the expression less greedy, but (depending where I add the dot-star), I either get no result or I get an inaccurate response

How to&Answers:

To match the first match on a line you may add ^.*? at the beginning of the pattern, wrap what you have with capturing parentheses and set the Multiline regex property to True. Your match is inside match.Submatches(0).

regEx.Pattern = "^.*?((?:\b\d{1,2}\D{0,3})?\b(?:Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|June?|July?|Aug(?:ust)?|Sep(?:tember)?|Oct(?:ober)?|(?:Nov|Dec)(?:ember)?)\D?(?:\d{1,2}\D?)?\D?(?:(?:19[7-9]\d|20\d{2})|\d{2}))"
regEx.Multiline = True

See the regex demo.