matlab字符串的操作及正则表达式regexp

来源:互联网 发布:自制名片软件下载 编辑:程序博客网 时间:2024/06/05 03:43

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} =   titletokens{2}{1} =   pcelldisp(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

原创粉丝点击