Reputation: 8241
How would I write a regular expression (Python or Java) that matches strings that contain exactly 10 digits (0-9). I don't care if it contains any other characters, and the 10 digits do not have to be consecutive. For example, I want to following strings to match: "2fdf675&*85y989$%#0" and "3h2j9f88__+=123..54". Any ideas on how to go about doing this??
Upvotes: 2
Views: 1478
Reputation: 424983
Here's a regex and java code:
if (str.matches("(\\D*\\d){10}\\D*")) // FYI ^ and $ are implied in java
But in java here's an easier way to comprehend:
if (str.replaceAll("\\D", "").length() == 10)
This just removes all non-digits and checks the length of what's left.
Upvotes: 0
Reputation: 93636
It will probably be clearer if you don't try to cram everything into one regex. I don't know Java or Python, but here's what you could do in Perl:
$str =~ s/\D//g; # Remove all non-digit characters
if ( length($str) == 10 ) ... # Must be left with 10 characters.
Upvotes: 0