Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return the first five digits using Regular Expressions

Tags:

regex

How do I return the first 5 digits of a string of characters in Regular Expressions?

For example, if I have the following text as input:

15203 Main Street Apartment 3 63110

How can I return just "15203".

I am using C#.

like image 443
Flea Avatar asked Dec 05 '22 02:12

Flea


1 Answers

This isn't really the kind of problem that's ideally solved by a single-regex approach -- the regex language just isn't especially meant for it. Assuming you're writing code in a real language (and not some ill-conceived embedded use of regex), you could do perhaps (examples in perl)

# Capture all the digits into an array
my @digits = $str =~ /(\d)/g;
# Then take the first five and put them back into a string
my $first_five_digits = join "", @digits[0..4];

or

# Copy the string, removing all non-digits
(my $digits = $str) =~ tr/0-9//cd;
# And cut off all but the first five
$first_five_digits = substr $digits, 0, 5;

If for some reason you really are stuck doing a single match, and you have access to the capture buffers and a way to put them back together, then wdebeaum's suggestion works just fine, but I have a hard time imagining a situation where you can do all that, but don't have access to other language facilities :)

like image 100
hobbs Avatar answered Mar 07 '23 20:03

hobbs