D_Bester
D_Bester

Reputation: 5931

Regex match a specific string

I am trying to extract the string <Num> from within Barcode(_<Num>_).PDF using Regex. I am looking at Regular Expression Language - Quick Reference but it is not easy. Thanks for any help.

    Dim pattern As String = "^Barcode(_+_)\.pdf" 
    If Regex.IsMatch("Barcode(_abc123_).pdf", pattern) Then
        Debug.Print("match")
    End If

Upvotes: 2

Views: 1590

Answers (3)

D_Bester
D_Bester

Reputation: 5931

Just for the record, this is what I ended up using:

    'set up regex
    'I'm using + instead of * in the pattern to ensure that if no value is
    'present the match will fail
    Dim pattern As String = "Barcode\(_(.+)_\)\.pdf"
    Dim r As Regex = New Regex(pattern, RegexOptions.IgnoreCase)

    'get match
    Dim mat As Match
    mat = r.Match("Barcode(_abc123_).pdf")

    'output the matched string
    If mat.Success Then
        Dim g As Group = mat.Groups(1)
        Dim cc As CaptureCollection = g.Captures
        Dim c As Capture = cc(0)
        Debug.Print(c.ToString)
    End If

.NET Framework Regular Expressions

Upvotes: 0

Kill Console
Kill Console

Reputation: 2023

I don't know the regex in VB, but I can offer you a website to examine the correctness of your regex: Regex Tester. In this case, if the <Num> is numbers, you can use "Barcode(_\d+_).pdf"

Upvotes: 1

cwa76
cwa76

Reputation: 154

If you are trying to not only match but also READ the value of into a variable, then you will need to call the Regex.Match method instead of simply calling the boolean isMatch method. The Match method will return a Match object that will let you get to the groups and captures from your pattern.

Your pattern would need be something like "Barcode\(_(.*)_\)\.pdf"-- note the inner parenthesis which will create a capture group for you to obtain the value of the string between the underscores.. See a MSDN docs for examples of almost exactly what you are doing.

Upvotes: 1

Related Questions