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
Matching function of a regular expression in excel?
提问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 Like
method;
您可以使用内置Like
方法;
if "DE0006231009" like "[A-Za-z][A-Za-z]##########" then ...