How could I find out if there are any special characters in my string? Suppose I have the string '1asdf?', how could I detect if there is a special character in there?

2 件のコメント

Cedric
Cedric 2017 年 9 月 10 日
What is the purpose? Do you need a true/false type of answer, the position of special characters, to eliminate them, ..? How to you define "special"?
William Nelson
William Nelson 2017 年 9 月 10 日
編集済み: Cedric 2017 年 9 月 10 日
I need a true and false answer and a special character is anything that is not abc or 123. ?"{} would all be special characters.

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

 採用された回答

Steven Lord
Steven Lord 2017 年 9 月 10 日

2 投票

Use isstrprop with category 'alphanum' to identify letters and digits.

その他の回答 (1 件)

per isakson
per isakson 2017 年 9 月 10 日
編集済み: per isakson 2017 年 9 月 10 日

1 投票

>> str = regexp( '1asdf?', '[^\w]', 'match' )
str =
'?'
where I defined not being special as "Any alphabetic, numeric, or underscore character. For English character sets, \w is equivalent to [a-zA-Z_0-9]"
In response to comment
"I need a true and false answer and a special character is anything that is not abc or 123. ?"{} would all be special characters."
>> str = '1a$s#df?';
>> is_special = false( size( str ) );
>> is_special( regexp( str, '[^a-zA-Z0-9.?"{}]' ) ) = true
is_special =
0 0 1 0 1 0 0 0
>>
I assumed that "123" is short for "0123456789". However, after a second reading
is_special( regexp( str, '[^123abc]' ) ) = true
is_special =
0 0 1 1 1 1 1 1
>>

4 件のコメント

Cedric
Cedric 2017 年 9 月 10 日
'[^\w]' = '\W'
per isakson
per isakson 2017 年 9 月 10 日
Good point!
Cedric
Cedric 2017 年 9 月 10 日
編集済み: Cedric 2017 年 9 月 10 日
Given your comment after Per answered, William, which seems to indicate that the underscore '_' is a special character, I think that you want a variant of Per's solution:
>> specials = regexp( '1as_df?980{}', '[^A-Za-z0-9]', 'match' )
specials =
1×4 cell array
'_' '?' '{' '}'
or
>> specialsPos = regexp( '1as_df?980{}', '[^A-Za-z0-9]', 'start' )
specialsPos =
4 7 11 12
or
>> isOk = isempty( regexp( '1as_df?980{}', '[^A-Za-z0-9]', 'start' ))
isOk =
logical
0
where the pattern fully defines characters that are not special, and eliminate the underscore which is not matched by \W.
per isakson
per isakson 2017 年 9 月 10 日
A typesetter shall follow the manuscript even if it blows out of the window. Does that make sense in English?
One more answer
>> isvarname('1a$s#df?')
ans =
0

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

カテゴリ

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

質問済み:

2017 年 9 月 10 日

回答済み:

2017 年 9 月 10 日

Community Treasure Hunt

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

Start Hunting!

Translated by