How to ascertain number of special characters in a string?

If there is array containing 5 different strings, how can I ascertain the number of special characters in each separate string?

回答 (2 件)

Jeff E
Jeff E 2013 年 11 月 8 日

0 投票

blah = ' This line contains * some & special ( chars_!@#';
idx = regexp(blah, '_|!|\*');
special_count = size(idx, 2);

1 件のコメント

Walter Roberson
Walter Roberson 2013 年 11 月 8 日
I would simplify the pattern to '[_!*]' instead of '_|!|\*'
If you do use [] then if you have "-" (dash, minus sign) in the list, ensure that it is either right after the "[" or right before the "[". Also if you include "^" in the list, ensure that it is not right after the "["

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

Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 8 日

0 投票

s={'abc/d?' 'abcd' 'Abc123\'}
out=cellfun(@numel,regexp(s,'[^a-zA-A0-9]+','match'))

3 件のコメント

Walter Roberson
Walter Roberson 2013 年 11 月 8 日
Space is not usually considered to be a "special character". Characters in non-Roman alphabets are not usually considered to be special characters either. For example "é" would normally be considered an alphabetic character rather than a "special character".
Azzi Abdelmalek
Azzi Abdelmalek 2013 年 11 月 8 日
編集済み: Azzi Abdelmalek 2013 年 11 月 8 日
s={'abc/d?' ' abé cd' 'Abc123\'}
out=cellfun(@numel,regexp(s,'[^\w\s]+','match'))
Walter Roberson
Walter Roberson 2013 年 11 月 9 日
\w Any alphabetic, numeric, or underscore character. For English character sets, \w is equivalent to [a-zA-Z_0-9]
Notice that includes underscore.
Also the wording there hints that what \w matches might be locale-dependent, such as LANG=en-CA (Canadian English) perhaps having \w match something different than LANG=en-FR (Canadian French)

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

カテゴリ

ヘルプ センター および File ExchangeCharacters and Strings についてさらに検索

質問済み:

2013 年 11 月 8 日

コメント済み:

2013 年 11 月 9 日

Community Treasure Hunt

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

Start Hunting!

Translated by