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.
0 件のコメント
回答 (2 件)
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.
0 件のコメント
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 Center および File Exchange で Characters and Strings についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!