【问题标题】:How can I parse a string into letters, digits, etc., in MATLAB?如何在 MATLAB 中将字符串解析为字母、数字等?
【发布时间】:2010-12-09 19:32:51
【问题描述】:

我在 MATLAB 中有一个类似 '12hjb42&34ni3&(*&' 的字符串。

我想通过正则表达式或其他更简单的方法将数字和字母以及其他所有内容分开。我该怎么做?

【问题讨论】:

  • 你能澄清一下 - 你想分开每个序列是全字母数字还是全非字母数字?或者您想将所有字母数字拉到一个字符串,将非字母数字拉到另一个字符串?您是希望将“digits & letters”和“everything else”分成两组,还是将“digits”、“letters”和“everything else”分成三组?

标签: regex matlab string


【解决方案1】:

比起使用正则表达式,我觉得用函数ISSTRPROP会更方便:

str = '12hjb42&34ni3&(*&';                   %# Your sample string
alphaStr = str(isstrprop(str,'alpha'));      %# Get the alphabetic characters
digitStr = str(isstrprop(str,'digit'));      %# Get the numeric characters
otherStr = str(~isstrprop(str,'alphanum'));  %# Get everything that isn't an
                                             %#   alphanumeric character

这会给你这些结果:

alphaStr = 'hjbni'
digitStr = '1242343'
otherStr = '&&(*&'

如果你真的想使用REGEXP,你可以这样做:

matches = regexp(str,{'[a-zA-Z]','\d','[^a-zA-Z\d]'},'match');
alphaStr = [matches{1}{:}];
digitStr = [matches{2}{:}];
otherStr = [matches{3}{:}];

【讨论】:

    【解决方案2】:

    我不认为正则表达式可以处理这个问题,除非你提前知道你有多少个数字/字符串/其他块。例如,在 'st34*' 中有 3 个块,所以这可以工作:

    regexprep('st34*', '([A-Za-z]+|\d+|\W+)([A-Za-z]+|\d+|\W+)([A-Za-z]+|\d+|\W+)', ...
     '$1 $2 $3')
    

    如果您不知道块的数量,您可以转换为 int 并分桶到您的 3 个类别中,然后查看类别更改的位置以找到您的断点。

    n = int32('st34a');
    idx = zeros(size(n));
    idx(ismember(n, int32('0'):int32('9'))) = 1;
    idx(ismember(n, int32('a'):int32('z'))) = 2;
    idx(ismember(n, int32('A'):int32('Z'))) = 2;
    idx = diff(idx) ~= 0;  % these are the breakpoints where your string changes type
    

    我还没有测试过这个,但是这样的东西应该可以工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多