开发者

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

I've been tr开发者_JAVA技巧ying 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


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


Use the expression <(\d+)>. Execute the regular expression using

Set matches = expr.Execute(text)
If matches.Count > 0 Then
    result = matches(0).Submatches(0)
End If

The Submatches collection contains strings that correspond to the parenthesis groupings in the expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜