Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression - How to find a match within a match?

Tags:

regex

vbscript

I've been trying to do the following using VBs Regular Expression object but could not find an easy way to do it. Is there anyone who could provide some suggestions?

For example, I have a string "12<56>89", I would like to get the string inside the "<>" which should be "56" in this case. What I'm currently doing is I try to find the expression "<\d+>" which will return <56>. Then I try to find the expression "\d+" from the result of the first match which will return 56.

I don't like this way because it needs to call the function twice. I'm wondering if it's possible to get the string inside the "<>" using just one regular expression? Thank you!

Thanks, Allen

like image 695
Allen Avatar asked Feb 09 '11 23:02

Allen


People also ask

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What is ?: In regex?

It indicates that the subpattern is a non-capture subpattern. That means whatever is matched in (?:\w+\s) , even though it's enclosed by () it won't appear in the list of matches, only (\w+) will.

What is \r and \n in regex?

Matches a form-feed character. \n. Matches a newline character. \r. Matches a carriage return character.

How do I search for a word in a regular expression?

Choose View->Show Search Options to show the Search Options pane. Expand the Search Mode drop-down and choose Regular Expressions or MS Word Wildcards. You will notice that an icon will appear next to the Source Term and Target Term fields to indicate that you are in the selected mode.


1 Answers

Use the expression "<(\d+)>"

You can then access all matches as a collection. Your regex can match more than once if you set RegEx.Global = True. The first match is found in var(0), second at var(1). Submatch groups are found at var(0).SubMatches(0), etc. If you're only doing it once, you can one line it:

Dim RegEx : Set RegEx = New RegExp
RegEx.Pattern = "<(\d+)>"
Dim strTemp : strTemp = "12<56>89"
WScript.Echo RegEx.Execute(strTemp)(0).SubMatches(0)

Test out your regular expressions here: http://www.regular-expressions.info/vbscriptexample.html

like image 136
Jeff Lamb Avatar answered Nov 04 '22 08:11

Jeff Lamb