Find exact string match in a cell of strings

2 ビュー (過去 30 日間)
Milan Prakash
Milan Prakash 2022 年 5 月 7 日
コメント済み: Milan Prakash 2022 年 5 月 7 日
Hello,
I would like to match a string in a cell array of strings.
For example I want to do exact match of str
str = 'XYZ1'
in a cell array of C
C = {'This is XYZ1','This is XYZ11', 'This is XYZ1111','This is XYZ1.0'}
Problem with using regexp -
fun = @(x) regexp(x,'XYZ1','match')
fidx = cellfun(fun, C)
or contains -
fun = @(x) contains(x,'XYZ1')
fidx = cellfun(fun, C)
is that all four cell strings contains some version of the string 'XYZ1' I am looking for. Kindly let me know if I can change something with regexp (there is help but its bit confusing for me with respect to using conditions/tokens etc.) or anything else I can use.
Regards,
Milan
  2 件のコメント
Jan
Jan 2022 年 5 月 7 日
編集済み: Jan 2022 年 5 月 7 日
What is exactly not accepted after the keyword 'XYZ1'? Spaces, dots, letters, numbers, any other characters?
Does endsWith(C, 'XYZ1') solve the problem already?
Milan Prakash
Milan Prakash 2022 年 5 月 7 日
Thanks, endsWith works just fine. Have to check for the actual cell array whether it does the trick. XYZ1 is an example of identifier I am looking for. In the text file, there are particular identifiers named from X(1 to 5000). Now each identifier for example X1 or X100 has a specific operation associated with it hence its important to identify them correctly. There are no spaces or dots. Example cell array was just a random example.

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

採用された回答

Stephen23
Stephen23 2022 年 5 月 7 日
C = {'This is XYZ1','This is XYZ11', 'This is XYZ1111','This is XYZ1.0'};
str = 'XYZ1';
rgx = sprintf('%s(?=$|\\s)',str);
regexp(C,rgx,'match','once')
ans = 1×4 cell array
{'XYZ1'} {0×0 char} {0×0 char} {0×0 char}
  1 件のコメント
Milan Prakash
Milan Prakash 2022 年 5 月 7 日
Thanks, this works as well. Just for my case and I think I missed mentioning it and the end want the the index position where the desired string is. As such can either add few lines at the end of this code or use endsWith as pointed out in one of the other comments.

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

その他の回答 (0 件)

カテゴリ

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

製品


リリース

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by