2

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
3
  • You need a \d before the + otherwise you are just matching underscores Commented Mar 12, 2014 at 1:06
  • What's an example file name look like? Barcode_123_.pdf? Or something else? Commented Mar 12, 2014 at 1:10
  • like Barcode(_abc123_).pdf; could be numbers or string; I want the abc123 Commented Mar 12, 2014 at 1:12

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried that but it didn't match yet; I will check out the website you mentioned
Actually it varies by language... I will edit my answer, I think using Vb.net you will want to escape the real parentheses, not the grouping ones. ie "Barcode(_(.*)_)\.pdf"
1

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"

2 Comments

I tried your pattern with "Barcode(_123_).pdf" but it didn't match; I'll check out the Regex Tester
Thanks for the link to the tester; That's great!
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.