【问题标题】:Search for whole word in text in Matlab在 Matlab 中搜索文本中的整个单词
【发布时间】:2020-10-06 19:44:08
【问题描述】:

我尝试寻找特定的字符组合。组合如下:“文本”:

引号和冒号是其中的一部分。我用 Matlab 的 ismember() 函数尝试了它,但是,它总是单独检查每个字符,我无法搜索整个字符串。下面是一个可重现的例子。

ismember('"text":', '"text": asdf')
% What it returns:    1   1   1   1   1   1   1
% What I want it to return: 1

ismember('"text":', '"teasdfxt": asdf')
% What it returns:    1   1   1   1   1   1   1
% What I want it to return: 0

% I also tried the following options, both did not work
ismember(""text":", '"teasdfxt": asdf')
cellfun(@length, strfind('"text": asdf', '"text":'))

【问题讨论】:

  • 如果你有 MATLAB 2016b 或更高版本,也许contains?
  • ~isempty(strfind('"text": asdf', '"text":')) 怎么样?
  • 使用 @saastn 的代码我得到了 MATLAB 的建议,将其替换为以下代码:contains('"text": asdf', '"text":')。这很好用并回答了我的问题。

标签: string matlab char


【解决方案1】:

在字符串中使用包含和写入引号

使用 contains 就像上面的评论所暗示的那样是检查子字符串是否存在于另一个字符串中的好方法。此外,如果您希望字符串包含单引号 ' 或双引号 ",则可以通过键入两次 ""'' 来编写它们。完成此操作后,最好在工作区窗口中打开变量以查看字符串是否按预期出现。

%Checking if string exists%
String_Of_Interest = """text"":";
String_To_Search = """text"": asdf";

contains(String_To_Search,String_Of_Interest)

在 MATLAB 中处理字符串时需要注意的重要一点是

字符串与字符数组

'Text' → 返回一个维度为 1 x 4 的字符数组。

“文本”→返回一个字符串。

String = "text";
Character_Array = 'text';

使用 MATLAB 版本:R2019b

【讨论】:

  • 感谢您的解释。不幸的是,我感兴趣的是"text": 而不是"text"。我还必须能够搜索:。 saastn 的评论对我有用。
  • @00koeffers 我的错误错过了冒号。我刚刚编辑了答案以包含它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 1970-01-01
  • 2022-12-22
  • 2014-03-10
  • 2016-08-01
  • 1970-01-01
相关资源
最近更新 更多