正则表达式 - 如何在匹配中找到匹配? [英] Regular Expression - How to find a match within a match?

查看:49
本文介绍了正则表达式 - 如何在匹配中找到匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 VBs 正则表达式对象执行以下操作,但找不到一种简单的方法来执行此操作.有没有人可以提供一些建议?

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?

例如,我有一个字符串12<56>89",我想将字符串放在<>"中,在这种情况下应该是56".我目前正在做的是尝试找到将返回 <56> 的表达式<\d+>".然后我尝试从将返回 56 的第一个匹配结果中找到表达式\d+".

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!

谢谢,艾伦

推荐答案

使用表达式<(\d+)>"

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

然后您可以将所有匹配项作为集合访问.如果您设置 RegEx.Global = True,您的正则表达式可以匹配多次.第一个匹配在 var(0) 中找到,第二个在 var(1) 中.子匹配组可以在 var(0).SubMatches(0) 等处找到.如果你只做一次,你可以一行:

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)

在这里测试您的正则表达式:http://www.regular-expressions.info/vbscriptexample.html

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

这篇关于正则表达式 - 如何在匹配中找到匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆