How do I compare the numbers that I have with the given pattern?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
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 comentarios
Respuestas (2)
John D'Errico
el 23 de Feb. de 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 comentarios
Chris McComb
el 23 de Feb. de 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) == '-'
Ver también
Categorías
Más información sobre Characters and Strings en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!