vba excel中正则表达式的匹配功能?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19784587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 00:16:02  来源:igfitidea点击:

Matching function of a regular expression in excel?

regexexcelvbaexcel-2010

提问by Anna.Klee

I have several cells in my sheet which contain an ISIN.

我的工作表中有几个包含ISIN 的单元格。

Here is an example of an ISIN: DE0006231004

以下是 ISIN 的示例: DE0006231004

I have created a regular expression which matches the ISIN: ^[a-zA-Z]{2}[0-9]{10}$

我创建了一个与 ISIN 匹配的正则表达式: ^[a-zA-Z]{2}[0-9]{10}$

I want to match this regex on my cell and give a 1 if it matches otherwise a 0.

我想在我的单元格上匹配这个正则表达式,如果匹配则为 1,否则为 0。

Is this possible with a function?

这可以通过函数实现吗?

回答by Kazimierz Jawor

The following function will do what you need. It will return either 0 (zero) if string doesn't match or 1 (one) if the string matches to pattern.

以下功能将满足您的需求。如果字符串不匹配,它将返回 0(零),如果字符串与模式匹配,则返回 1(一)。

Function MatchISIN(ISIN As String)

    Dim regEx As Object
    Set regEx = CreateObject("vbscript.regexp")

    regEx.Pattern = "^[a-zA-Z]{2}[0-9]{10}$"
    regEx.IgnoreCase = True
    regEx.Global = True

    Dim Matches As Object
    Set Matches = regEx.Execute(ISIN)

    MatchISIN = Matches.Count

End Function

回答by Alex K.

You could use the built-in Likemethod;

您可以使用内置Like方法;

if "DE0006231009" like "[A-Za-z][A-Za-z]##########" then ...