matlab字符串的操作及正則表達式regexp

matlab字符串的操作及正則表達式regexp

1.字符串的操作在參考文獻3中已經基本列舉完善,用法及其簡單,不過多贅述。
主要的字符串操作函數有如下:

length(str)%計算字符的長度
strcat(str1,str2)%連接字符串
strncmp(str1,str2,n)%比較字符串的前n個字符
strcmp(str1,str2)%%比較字符串
strfind(str,pattern)%找到字符串範圍位置
deblank(str)%裁切字符串的尾部空格
strtrim(str) %裁切字符串的開頭和尾部的空格,製表,回車符

2.正則表達式

regexp——用於對字符串進行查找,大小寫敏感;
regexpi——用於對字符串進行查找,大小寫不敏感;
regexprep——用於對字符串進行查找並替換。

在參考文獻1,2中也介紹的較爲詳盡了,我只舉出一些matlab的help文檔中的例子加以闡述即可。

1.字符分割

str = ['Split ^this string into ^several pieces'];
expression = '\^';
splitStr = regexp(str,expression,'split')
splitStr = 

    'Split '    'this string into '    'several pieces'

\^代表轉義字符,該語法的目的是將^的左右字符分隔開,並各自存儲在cell中。
2.字符匹配

str = 'EXTRA! The regexp function helps you relax.';
expression = '\w*x\w*';
matchStr = regexp(str,expression,'match')
matchStr = 

    'regexp'    'relax'

正則表達式\w*表示匹配任意數量的字符,包括none。

3.匹配分割

str = 'She sells sea shells by the seashore.';
expression = '[Ss]h.';
[match,noMatch] = regexp(str,expression,'match','split')
match = 

    'She'    'she'    'sho'


noMatch = 

    ''    ' sells sea '    'lls by the sea'    're.'

[Ss]h表示匹配Sh和sh兩個字符

4.正則表達式(\w+)(.*)

str = '<title>My Title</title><p>Here is some text.</p>';
expression = '<(\w+).*>.*</\1>';
[tokens,matches] = regexp(str,expression,'tokens','match');
celldisp(tokens)
tokens{1}{1} =
   title

tokens{2}{1} =
   p
celldisp(matches)
matches{1} =
   <title>My Title</title>

matches{2} = 
   <p>Here is some text.</p>

(\w+).*匹配與(\w*)一樣匹配任意字符,

str = sprintf('abc\n de');
expression = '.*';
matchStr = regexp(str,expression,'match')
matchStr = 

    [1x7 char]

匹配一切字符
6. dotexceptnewline

matchStrNoNewline = regexp(str,expression,'match','dotexceptnewline')
matchStrNoNewline = 

    'abc'    ' de'

dotexceptnewline分離每行文本,並返回每行文本的數值,文本換行使用\n分隔開。
7. lineanchors

expression = '.$';
lastInLine = regexp(str,expression,'match','lineanchors')
lastInLine = 

    'c'    'e'

$提取每行文本的最後一個字符,^提取每行文本的第一個字符

matlab的正則跟python的正則表達式很相似。
關於python的正則表達式的使用方法如下
http://www.jianshu.com/p/59e77412db0b

參考文獻:
1. http://blog.csdn.net/yf210yf/article/details/42421523
2. http://blog.csdn.net/u012730840/article/details/18969721
3. http://www.cnblogs.com/emanlee/archive/2012/09/13/2683912.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章