VBA Regular Expression Matching Pattern

天涯浪子 提交于 2020-07-23 07:55:20

问题


I have records like RF123456789, RF1234567890 etc.

I just want to match the records which are starting with 'RF' followed by exactly 9 digits of number. If it is more than 9 digit or less than 9 digit It should show Invaid. I have wrote the below code, but the problem with this is , if the number is more than 9 also it is showing valid. I understand that I have written to check only if it starts with RF and followed by 9 digits, so in case of 10 digits it is obviously matching my pattern. Is there any way I could restrict it for only 9 digits rather that 10?

Set myrange = Range("C2:C" & Rng)
For Each c In myrange
    strinput = c.Value
    patn = "([r|R][f|F][0-9]{9})"
    If patn <> "" Then
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = patn
        End With
        If regex.Test(strinput) Then
            c.Offset(0, 5) = "Valid"
        Else
            c.Offset(0, 5) = "Invalid"
        End If
    End If

    ''checking Column D and E are matching or not''
    If c.Offset(0, 1) <> "" Then
        If c.Offset(0, 1) = c.Offset(0, 2) Then
            c.Offset(0, 6) = "Matching"
        Else
            c.Offset(0, 6) = "Not Matching"
        End If
    Else
        c.Offset(0, 6) = "Empty"
    End If
Next

回答1:


You shouldn't use regex for this at all. A simple Like statement would do.

Just use strinput Like "RF#########". That returns true if it starts with RF (case insensitive) and then has 9 digits, else false.




回答2:


Wrap it in boundaries?

\bRF\d{9}\b

Try here

\bRF\d{9}\b / gm

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)

RF matches the characters RF literally (case sensitive)

\d{9} matches a digit (equal to [0-9])

{9} Quantifier — Matches exactly 9 times

\b assert position at a word boundary (^\w|\w$|\W\w|\w\W)


Update:

There are lots of ways to state having a lead of 2 numbers or RF. One might be:

\b(\d{2}|RF)\d{9}\b

Try it.

Someone more familiar with regex can no doubt advise on efficient regex methods.




回答3:


You can also use string functions like left() right() len() and isnumeric()

To check that the entire string is 11 characters long (RF + 9 digits) you could use:

If len(yourstring) = 11 then

To check that the string starts with RF use:

If left(yourstring,2)="RF" then

To check that the last 9 characters are numbers only first dimension a variant:

dim num_check as variant
num_check = right(yourstring,9)
If isnumeric(num_check) = False then

You can nest or combine these if statements to get the desired result.



来源:https://stackoverflow.com/questions/52520220/vba-regular-expression-matching-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!