How I would determine if a string contains multiple substrings?
254 ビュー (過去 30 日間)
古いコメントを表示
I'd like to know if a string has multiple substrings (e.g, words) in it.
For example:
myString = "This has some words in it.";
I would want to know if that string has "This" AND "some". I know I can use "contains" to look for individual substrings, but I want to know if ALL substrings are in a string.
0 件のコメント
採用された回答
その他の回答 (3 件)
Bruno Luong
2023 年 8 月 4 日
編集済み: Bruno Luong
2023 年 8 月 4 日
myString = "This has some words in it.";
subStrings = ["This","some"];
hasAllSubstrings = isequal(regexp(myString, subStrings, 'once', 'match'), subStrings)
0 件のコメント
Les Beckham
2023 年 2 月 23 日
編集済み: Les Beckham
2023 年 2 月 23 日
myString = "This has some words in it.";
if contains(myString, "This") && contains(myString, "some")
disp Yes
else
disp No
end
Steven Lord
2023 年 11 月 10 日
myString = "This has some words in it.";
s = split(myString)
whichWordsAreIn = ismember(["some"; "in"], s)
allWordsIn = all(whichWordsAreIn)
You can combine this into one command if you want; I showed temporary variables to illustrate each step. For exclusions you want to wrap the ismember call in ~any() instead of all.
2 件のコメント
Steven Lord
2023 年 11 月 16 日
I neglected to remove punctuation from the string before splitting it. The isstrprop function could help with this (though you'd have to be careful with punctuation included as part of a word, like "you'd" as I wrote earlier in this phrase.)
The accepted answer has a similar problem, if you change the text to be examined to include a word that contains as part of it one of the substrings being searched for.
myString = "This has something words in it.";
subStrings = ["This","some"]; % myString has "something", does that match "some"?
hasAllSubstrings = all(arrayfun(@(substr) contains(myString, substr, 'IgnoreCase', true), subStrings))
For more general cases and processing lots of data, you may want to use the functionality for analyzing text data provided in Text Analytics Toolbox.
参考
カテゴリ
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!