2010-12-09 26 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 

我還沒有測試過這個,但是像這樣的東西應該可以工作。

相關問題