2010-12-09 27 views
2

在MATLAB中,我有一个像这样的字符串'12hjb42&34ni3&(*&'如何在MATLAB中将字符串解析为字母,数字等?

我想通过正则表达式或其他更简单的方法来分隔数字和字母以及其他一切。我怎样才能做到这一点?

+0

您能否澄清一下 - 您是否要分隔每个字母数字或全部非字母数字的序列?还是你想把所有的字母数字都拉到一个字符串中,而非字母数字是否要拉到另一个字符串?你想把“数字和字母”和“其他”分成两组,即“数字”,“字母”和“其他”作为三组吗? – 2010-12-09 19:51:12

回答

9

而不是使用正则表达式的,我认为它会更容易使用的功能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}{:}]; 
0

我不认为正则表达式可以处理这个,除非你知道你有多少个数/字符串/其他块提前。例如,在“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 

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

相关问题