我在Matlab中有一个字符串,想要用另一个模式替换其中某些模式的第三个外观。我怎么能这样做?
例如:
str = 'ter-yu-ter-u-ter-hg';
patternRemove = 'ter';
patternAdd = 'mov';
答案:
str = 'ter-yu-ter-u-mov-hg';
答案 0 :(得分:1)
抱歉,我无法为您提供更多帮助,但我不知道您是如何在Matlab中进行的。如果我试图解决这个问题,我就是这样做的。
<?php
$i = 0; // SET A DEFAULT VALUE FOR OUR COUNTER
$str = 'ter-yu-ter-u-ter-hg-ter-as-b-ter-a-sdf-w-ter-s-ter-asd'; // TEXT TO WORK ON
$remove = 'ter'; // TEXT TO REPLACE EACH THIRD OCCURRENCE OF
$replace = 'mov'; // TEXT TO REPLACE EACH THIRD OCCURRENCE WITH
// USE A CALLBACK FUNCTION TO CHECK TO SEE HOW MANY TIMES IT'S FOUND A MATCH
// INCREMENT THE COUNTER EACH TIME
// IF THE COUNTER IS 3, RESET IT TO ZERO AND MAKE THE REPLACEMENT
$string = preg_replace_callback('/'.$remove.'/', function($m) use(&$i, $remove, $replace) {$a = $remove; if (++$i == 3) {$i = 0; $a = $replace;} return $a;}, $str);
print $string;
这输出以下内容:
ter-yu-ter-u-mov-hg-ter-as-b-ter-a-sdf-w-mov-s-ter-asd
如果您没有与preg_replace_callback
类似的功能,则可能会在搜索字词中将其分成多个段,并在remove
处分开。然后遍历所有字符串部分并每次递增计数器。如果计数器除以3的余数为零,则应用替换。
以下是使用foreach
:
// SET THE DEFAULTS
$i = 0;
$str = 'ter-yu-ter-u-ter-hg-ter-as-b-ter-a-sdf-w-ter-s-ter-asd';
$remove = 'ter';
$replace = 'mov';
$final_string = ''; // THIS WILL BE OUR OUTPUT STRING LATER
// BREAK APART THE STRING INTO AN ARRAY OF MATCHES, BASED ON THE $remove VALUE
$matches_for_remove = explode($remove, $str);
// LOOP THROUGH EACH ITEM IN THE ARRAY
foreach ($matches_for_remove AS $match) {
// SET THE DEFAULT STRING TO $remove
$replacement_string = $remove;
if (++$i % 3 == 0) { // IF THE REMAINDER IS ZERO, THEN DO THE REPLACEMENT
$replacement_string = $replace;
}
// IF IT'S NOT THE END, APPEND THE remove OR replace PORTION ON TO THE END
if ($i == count($matches_for_remove)){
$final_string .= $match;
}
else {
$final_string .= $match.$replacement_string;
}
}
print $final_string;
同样的示例,但使用for
循环而不是foreach
:
$str = 'ter-yu-ter-u-ter-hg-ter-as-b-ter-a-sdf-w-ter-s-ter-asd';
$remove = 'ter';
$replace = 'mov';
$final_string = '';
for ($i = 0; $i < count($matches_for_remove); $i++) {
$replacement_string = $remove;
if (($i + 1) % 3 == 0) {
$replacement_string = $replace;
}
if ($i == count($matches_for_remove) - 1) {
$final_string .= $matches_for_remove[$i];
}
else {
$final_string .= $matches_for_remove[$i].$replacement_string;
}
}
print $final_string;
再次,抱歉,如果我用PHP编写的例子没有任何意义。我理解这个概念,而不是如何将其转化为Matlab。但是,希望这至少会让你指出正确的方向。
答案 1 :(得分:1)
str = 'ter-yu-ter-u-ter-hg';
patternRemove = 'ter';
patternAdd = 'mov';
ind = regexp(str,patternRemove);
ii = ind(3);
strOut = [str(1:ii-1) patternAdd str(ii+numel(patternRemove):end)];