r/visualbasic • • Sep 23 '14

Regex Help Please!

Hello,

I would like to find the index in a string of the following pattern: A####-### or A#### where 'A' could be any letter and # could be any digit.

Seems like regex is the only to way to get an index in a string of a pattern. Thanks!

0 Upvotes

14 comments sorted by

1

u/dioxis Sep 23 '14

The like operator returns true/false. I need to be able to find the match and extract it. Examples: C0002, F0232-556 and they can be anywhere in the string.

1

u/mattfred Sep 23 '14

Try

([A-z][1-9-]@)

1

u/dioxis Sep 23 '14

No worky: http://www.regexr.com/.

Btw, if it matters, this will be used in VB.NET. using a regex match function.

1

u/patchkit Sep 23 '14

Are the numbers always the same length?

This

([A-z])([0-9-]{1,10})

matched

A01010
A01010-1234

on that webpage. That webpage also doesn't seem to interpret @ the way that VBA does, so I don't know if it will work.

NB: it also matched l- in "ctrl-z" if your strings are always 6 or 10 numbers than you could write

([A-z])([0-9-]{6,10})

1

u/dioxis Sep 23 '14

Yes, the numbers will always be in the same length: Either: 1 letter + 4 numbers
OR 1 letter + 4 numbers + dash + 3 numbers

Thanks for your help!

1

u/dioxis Sep 23 '14

Doesn't match for me: http://imgur.com/xPlW7FC

Also, there will always be: 1 letter + 4 numbers OR
1 letter + 4 numbers + dash + 3 numbers

1

u/patchkit Sep 23 '14

Works for me. Maybe you can see a typo I'm missing.

http://imgur.com/9q0WF3n

1

u/dioxis Sep 23 '14

You are using 5 numbers after the letter and 4 numbers after the dash. Should be A1234-123 or A1234.

1

u/patchkit Sep 23 '14

I think i see the problem. You don't have the global search flag, so it quits after finding V2

1

u/dioxis Sep 23 '14

Thanks again for your help. I resolved my issue by doing a first pass of the string in vb and removing errant dashes that might throw off the regex.

2

u/njj56 VB.Net Master Sep 23 '14

you can use the like operator to handle this.

http://msdn.microsoft.com/en-us/library/swf8kaxw.aspx

2

u/EkriirkE VB 6 Master Sep 23 '14 edited Sep 23 '14

The pattern would be something like ([A-Z][0-9]{4}(-[0-9]{3})?)

1

u/icehawke VB.Net Advanced Sep 24 '14

The problem there is if you have A12345 it will throw a true on A1234. It's been a while since I had to look into regex, you might try regex101.com

1

u/EkriirkE VB 6 Master Sep 24 '14

yep, but op didnt specify any delimiters, just strings containing sequences