0

Matlab 文档指出,可以替换 regexprep 中第 N 次出现的模式。我没有看到如何实现它,谷歌没有返回任何有用的东西。

http://www.weizmann.ac.il/matlab/techdoc/ref/regexprep.html

基本上我的字符串是 :,:,1 ,我想用任意数字替换第二次出现的 : 。根据文档:

regexprep(':,:,4',':','AnyNumber','N')

我不明白应该如何使用 N 选项。我试过'N',2或只是'2'。

请注意, : 的位置可以在任何地方。

我意识到除了 regexprep 之外还有其他方法可以做到这一点,但我不喜欢问题挥之不去。

谢谢您的帮助!

4

2 回答 2

0
regexprep(':,:,4',':','AnyNumber',2)

以上工作。

于 2012-07-03T19:14:24.650 回答
0

根据 MA​​TLAB 文档,regexprep 的一般语法是:

newStr = regexprep(str,expression,replace,option1,...optionM);

它在“str”中查找,找到匹配的“expression”,并将匹配的字符串替换为“replace”。有 9 个可用选项。其中八个是固定字符串,一个是整数。整数告诉要替换哪个匹配字符串。以下代码将所有参数设置为变量,查找匹配字符串的数量,并使用该信息仅替换最后一次出现。

str = ':,:,4'; 
expression= ':';
replace = num2str(floor(rand()*10)); 
                               % generate a single digit random number converted to string
idx = regexp(str, expression); % use regexp to find the number of matches
regexprep(str, expression, replace, length(idx)); % only replace the last one
于 2018-11-06T20:09:14.080 回答