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

转载 https://blog.csdn.net/awakeljw/article/details/76180599?locationNum=5&fps=1

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'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

\^代表转义字符,该语法的目的是将^的左右字符分隔开,并各自存储在cell中。 
2.字符匹配

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

    'regexp'    'relax'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

正则表达式\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.'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

[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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

(\w+).*匹配与(\w*)一样匹配任意字符,

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

    [1x7 char]
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

匹配一切字符 
6. dotexceptnewline

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

    'abc'    ' de'
  • 1
  • 2
  • 3
  • 4

dotexceptnewline分离每行文本,并返回每行文本的数值,文本换行使用\n分隔开。 
7. lineanchors

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

    'c'    'e'
  • 1
  • 2
  • 3
  • 4
  • 5

$提取每行文本的最后一个字符,^提取每行文本的第一个字符

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

猜你喜欢

转载自blog.csdn.net/u010751974/article/details/81195092