Understand if a char variable is an alphanumeric, a numeric or a string

31 ビュー (過去 30 日間)
Marco
Marco 2012 年 10 月 26 日
Hi,
How can I understand if a char is an alphanumeric (a1, ab2,...), a numeric or a string ?
thanks

回答 (4 件)

Sean de Wolski
Sean de Wolski 2012 年 10 月 29 日
編集済み: Sean de Wolski 2012 年 10 月 29 日
doc isstrprop

Azzi Abdelmalek
Azzi Abdelmalek 2012 年 10 月 26 日
編集済み: Azzi Abdelmalek 2012 年 10 月 26 日
class(var) % returns a class of var
ischar(var) % returns 1 if var is char, 0 otherwise
look at , isnan, isinf, isstruct, isnumeric,...

Evan
Evan 2012 年 10 月 26 日
編集済み: Evan 2012 年 10 月 29 日
If a char is numeric, the following command will return false:
isempty(str2double(s)) %where s is your char
One way I could think to see if a char is alphanumeric would be to use the following command:
help arrayfun
So, perhaps something like this:
arrayfun(@(x)isempty(str2double(x)),s) %where s is your char
That returns a true/false array where each element refers to a single character of your character array s. You can then compare the elements of that array to see if the char is numeric (all false), alphanumeric (mix of true and false) or a string (all true).
  2 件のコメント
Daniel Shub
Daniel Shub 2012 年 10 月 28 日
The STR2NUM function makes use of EVAL. Running EVAL on arbitrary unknown inputs is a disaster waiting to happen. At a minimum you should use STR2DOUBLE.
Evan
Evan 2012 年 10 月 29 日
I knew that str2double is preferred in most cases where one is dealing with scalar values, but I had never actually wandered across an explanation for why this is the case. I have modified my above answer. Thanks!

サインインしてコメントする。


Walter Roberson
Walter Roberson 2012 年 10 月 30 日
I do not know what you mean by "a string" in this context. All char variables are strings in MATLAB.
"numeric" is a subset of "alphanumeric". The string '12345' is both a string of numeric characters and a string of alphanumeric characters. Your example seems to imply that you are only interested in the cases that start with alphabetic characters and end with numeric, but that is not clear. What about '123abc' or 'ab12c3' ? Do you want to include any non-Latin characters such as umlauted vowels? Accented vowels? cedilla ?
You should be considering using regexp
>> if regexp('123abc', '^[A-Za-z0-9]+$');disp('yes');else disp('no');end
yes
The ^ $ around the pattern forces a match only if the string is exactly that pattern. If the pattern does not match then regexp() will return the empty array, which "if" will consider as being false.

カテゴリ

Help Center および File ExchangeCharacters and Strings についてさらに検索

製品

Community Treasure Hunt

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

Start Hunting!

Translated by