How do I compare the numbers that I have with the given pattern?

2 次查看(过去 30 天)
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.

回答(2 个)

John D'Errico
John D'Errico 2015-2-23
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.

Chris McComb
Chris McComb 2015-2-23
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) == '-'

类别

Help CenterFile Exchange 中查找有关 Characters and Strings 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by