How to return the first five digits using regular expressions

advertisements

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#.


it would depend on your flavor of Regex and coding language (C#, PERL, etc.) but in C# you'd do something like

string rX = @"\D+";
Regex.replace(input, rX, "");
return input.SubString(0, 5);

Note: I'm not sure about that Regex match (others here may have a better one), but basically since Regex itself doesn't "replace" anything, only match patterns, you'd have to look for any non-digit characters; once you'd matched that, you'd need to replace it with your languages version of the empty string (string.Empty or "" in C#), and then grab the first 5 characters of the resulting string.