在matlab中搜索特定区域

search in specific region in matlab

我将在 matlab 中替换文本文件中的特殊单词,但只是括号中的单词“[]”,而不是所有单词。例如我有这样的文本:

this is a [test]
I'm going to replace just test in [] not the other [test].

我要用 test 1 替换单词 test。结果应该是:

this is a [test1]
I'm going to replace just test in [] not the other [test1].

我需要推动和弹出括号吗?或者有什么简单的方法?

这需要正则表达式 (regexp)。我自己不是专家,但让我告诉你一种方法(尽管可能有更优雅的解决方案):

使用 regexp 查找括号内出现的所有 test

regexp(txt,['\[[^\]]*(',word,')[^\]]*\]']);
  • \[ 以 [
  • 开头
  • [^\]]* 表示不属于 ]
  • 的任意数量的字符
  • (,)仅用于分组
  • word 就是您要找的。
  • [^\]]* 再次,对于任何数量的字符不是 ]
  • \] 以 ]
  • 结尾

您可以验证它是否找到了正确的事件(对于下面的示例):

regexp(txt,['\[[^\]]*(',word,')[^\]]*\]'],'match')
ans = 
    '[test]'    '[asdf test asdf]'

使用 tokenExtents,您将得到一个元胞数组,其中每个元胞都是一个向量 [start,end]。有了这些,你现在就可以替换文字了。

% Create example
txt = 'I''m going to replace just test in [] not the other [test] but still [asdf test asdf].';
word = 'test';
newWord = 'test1';

% Find all occurrences with regexp
ind = regexp(txt,['\[[^\]]*(',word,')[^\]]*\]'],'tokenExtents');

% Build new string
newTxt = txt(1:ind{1}(1)-1);  % first part
for k=1:size(ind,2)-1         % all middle parts
    newTxt = [newTxt,newWord,txt(ind{k}(2)+1:ind{k+1}(1)-1)];
end
newTxt = [newTxt,newWord,txt(ind{k+1}(2)+1:end)]; % last part

免责声明:我不得不承认,特别是构建字符串可能会更好。也许有人想出了更好的解决方案。

我不是正则表达式方面的专家,所以我不能用一个表达式来完成:

我将采用与 hbaderts:

相同的符号
txt = 'I''m going to replace just test in [] not the other [test] but still [asdf test test asdf].';
word = 'test';
newWord = 'test1';

替换括号内的所有匹配项:

这首先找到匹配的括号,然后通过 arrayfun 将数据提取到单元格中,使用 strrep 替换您的单词,然后再次连接单元格。

%%// Find all opening and matching closing brackets
[start,stop] = regexp(txt,'\[[^\]]*\]');
%%// Separate the data into cells: 
foundBrackets = arrayfun(@(b,e) txt(b:e), start, stop, 'uni', 0);
beforefoundBrackets = arrayfun(@(b,e) txt(b:e),  [1,stop(1:end-1)+1],start-1, 'uni', 0);
%%// Replace the data in the bracket cells:
replacedBrackets = strrep(foundBrackets, word, newWord);
newTxtinCells = [reshape([beforefoundBrackets;replacedBrackets],1,[]),txt(stop(end)+1:end)];
%%// Cat cells
newTxt = cat(2,newTxtinCells{:});

替换括号内的单个事件:

在这种情况下,一个正则表达式就可以了:

newTxt = regexprep(txt,['\[([^\]]*)',word,'([^\]]*)\]'],['\[',newWord,'\]'])