matlab regexprep替换第n次出现

时间:2012-07-03 19:07:38

标签: regex matlab

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

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

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

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

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

请注意:位置可能在任何地方。

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

感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

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

以上作品。

答案 1 :(得分:0)

根据MATLAB文档,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
相关问题