Regex match help. match exactly 4 digit numbers

G

gnewsaccess

I'm new to regular expression and having trouble with this.

I need to match 4 digit numbers within the textbox.text.

the problem i'm having is that even though I set the match pattern as
"\d{4}", it matches the first 4 digits of any number that is longer
than 4 digits.

eg.) abcd 1234 ahfhud --> would work because it would get 1234
abcd 987654321 abcd 1234 --> would first match 9876,
although I only need 1234

here's my code



Public Function GetValue as String

Dim Value1, Pattern1 as String

Pattern1 = "\d{4}"

Value1 = Regex.Match( TextBox1.Text, Pattern1 )

Return Value1

End Function



How do I return only the first match that is composed of 4 digit
number? Would be also very nice if I can skip number that is embeded
in a word with other characters. (eg. abcdb2345jddjidi - skip 3456
- ok )

Thanks in advance for your inputs.
 
E

eBob.com

First ...if you need to do any experimenting with regular expressions do
yourself a favor and get Expresso from UltraPico. It's free.

I use "capture groups" a lot so the first thing which occurs to me is

..*(?<four>\d{4})

But I suspect that the right answer is to use something called an "atomic
zero-width assertion"
(http://msdn.microsoft.com/en-us/library/h5181w5w.aspx). So ...

\d{4}$

is probably the right answer.

BUT ... your explanation of what you want was not crystal clear to me, so
maybe I misunderstood exactly what you want.

Good Luck (Get Expresso)

Bob
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top