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

조회 수: 2 (최근 30일)
Kratos
Kratos 2015년 2월 23일
댓글: Kratos 2015년 2월 23일
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