How do I compare the numbers that I have with the given pattern?
2 views (last 30 days)
Show older comments
Say I have bunch of phone numbers which are strings in parentheses and it has to be in this format (XXX-XXX-XXXX). How do I know that the string of numbers that I have is in that format? It can only have numbers and they have to be separated by hyphens.
0 Comments
Answers (2)
John D'Errico
on 23 Feb 2015
This is a classical problem for regexp.
regexp('123-456-7890','\d{3,3}-\d{3,3}-\d{4,4}')
ans =
1
regexp('123-456-789','\d{3,3}-\d{3,3}-\d{4,4}')
ans =
[]
regexp('0123-456-7890','\d{3,3}-\d{3,3}-\d{4,4}')
ans =
2
If regexp returns a 1, you have a match. An [] return or any number other than 1 means no match.
0 Comments
Chris McComb
on 23 Feb 2015
One way (though not the most elegant) would be to check the separately for the numbers, and then for the hyphens.
1. First, check to see if the string has numbers. Use a condition like:
sum(isstrprop(str, 'digit')) == 10
2. Next, check the 4th and 8th characters in the string to see if they are hyphens, like:
str(4) == '-'
See Also
Categories
Find more on Characters and Strings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!