regex - 如何在 Matlab 中使用 regexprep 将文本中的多个匹配项替换为不同的值

标签 regex matlab

我正在使用函数 regexprep在 Matlab 中用元胞数组中的值列表替换模式的几个实例。这个想法是用第一个值替换第一个匹配项,用下一个值替换第二个匹配项,依此类推。因此,每个匹配项都替换为元胞数组中的不同值。

来自documentation我读到:

If replace is a cell array of N character vectors and expression is a single character vector, then regexprep attempts N matches and replacements.

下面是我的任务示例(对于此示例,我们假设我知道只有 4 个匹配项):

% some text:
str = 'abc s;dlf kudnbv. soergi; abcva/.lge roins.br oianabca/ sergosr toibnsabc';
pattern = '([a][b][c])'; % the patern to match
values = {'111','222','333','444'}; % the cell array 
new_str = regexprep(str,pattern,values) % the actual raplace

结果:

new_str =
    '111 s;dlf kudnbv. soergi; 111va/.lge roins.br oian111a/ sergosr toibns111'

当然,这个结果是不正确的,因为所有的匹配项都被替换为元胞数组中的第一个值。

所以我用谷歌搜索了这个问题并找到了这个 explanation .显然函数 regexprep 一个一个地执行替换,所以在第一次替换之后,找到的第一个匹配是原来的第二个匹配,并且因为它被识别为第一个,所以它是替换为元胞数组中的第一个值 (111)。

我可以使用一个循环来解决这个问题,该循环每次都使用不同的值执行此任务:

new_str = str;
for k = 1:numel(values)
    new_str = regexprep(new_str,pattern,values(k),'once'); % raplace one value each time
end

结果:

new_str =
    '111 s;dlf kudnbv. soergi; 222va/.lge roins.br oian333a/ sergosr toibns444'

这正是我想要的。

我的问题是如何编写 pattern 或使用 regexprep 以便在没有循环的情况下获得相同的结果?
在我看来,我错过了一些关于如何使用这个功能的东西。我还要补充一点,我的真正问题在文本中有超过 100 个匹配项,因此使用像 ([a][b][c])(.*)([a][b][c] 这样的模式)(.*)([a][b][c])(.*)([a][b][c]) 和替换模式,如 111$2222$4333$6444(在这里给出正确的结果)并不是一个真正的选择。

任何帮助将不胜感激!

最佳答案

您可以制作一个基本的帮助字符串生成器并使用命令执行替换 token 。

例如:

classdef strgenerator < handle
    properties
        strs
        ii = 1
    end

    methods
        function self = strgenerator(strs)
            self.strs = strs;
        end

        function outstr = nextstr(self)
            outstr = self.strs{self.ii};

            self.ii = self.ii + 1;
            if self.ii > numel(self.strs)
                self.ii = 1;
            end
        end
    end
end

str = 'abc s;dlf kudnbv. soergi; abcva/.lge roins.br oianabca/ sergosr toibnsabc';
pattern = '([a][b][c])'; % the patern to match
values = strgenerator({'111','222','333','444'}); % the cell array 
new_str = regexprep(str,pattern,'${values.nextstr()}') % the actual raplace

为我们提供:

>> SOcode

new_str =

    '111 s;dlf kudnbv. soergi; 222va/.lge roins.br oian333a/ sergosr toibns444'

关于regex - 如何在 Matlab 中使用 regexprep 将文本中的多个匹配项替换为不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51969766/

相关文章:

javascript - 正则表达式负向前瞻以排除字符串

matlab - 在 Matlab 中传递参数

jquery - 密码强度不按规则工作

java - 字符串和 2 个字母

regex - 如何在Matlab/Octave中使用regexp(正则表达式)来查找重叠匹配

matlab - 如何将二进制值列表转换为int32类型?

matlab - 需要帮助在 Matlab 中绘制此函数

matlab - bundle 调整示例中的运行时错误 - matlab

python - 当 'text' 可能包含更多 {{ text }} block 时,如何用 re.sub() 替换表达式 {{ text }} ?

java - 否定复杂的正则表达式