js正则匹配

1.1. 反斜杠的问题

与大多数编程语言相同,正则表达式里使用"\"作为转义字符,这就可能造成反斜杠困扰。

假如你需要匹配文本中的字符"\",那么使用编程语言表示的正则表达式里将需要4个反斜杠"\\\\":

第一个和第三个用于在编程语言里将第二个和第四个转义成反斜杠,

转换成两个反斜杠\\后再在正则表达式里转义成一个反斜杠用来匹配反斜杠\。

这样显然是非常麻烦的。

Python里的原生字符串很好地解决了这个问题,这个例子中的正则表达式可以使用r"\\"表示。

同样,匹配一个数字的"\\d"可以写成r"\d"。

1.2.split

split(string[, maxsplit]) | re.split(pattern, string[, maxsplit]):
按照能够匹配的子串将string分割后返回列表。

maxsplit用于指定最大分割次数,不指定将全部分割。

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import re  
  2.    
  3. p = re.compile(r'\d+')  
  4. print p.split('one1two2three3four4')  
  5.    
  6. ### output ###  
  7. # ['one', 'two', 'three', 'four', '']  

1.3.findall

findall(string[, pos[, endpos]]) | re.findall(pattern, string[, flags]):
搜索string,以列表形式返回全部能匹配的子串。

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import re  
  2.    
  3. p = re.compile(r'\d+')  
  4. print p.findall('one1two2three3four4')  
  5.    
  6. ### output ###  
  7. # ['1', '2', '3', '4']  

1.4.finditer

finditer(string[, pos[, endpos]]) | re.finditer(pattern, string[, flags]):
搜索string,返回一个顺序访问每一个匹配结果(Match对象)的迭代器。

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import re  
  2.    
  3. p = re.compile(r'\d+')  
  4. for m in p.finditer('one1two2three3four4'):  
  5.     print m.group(),  
  6.    
  7. ### output ###  
  8. # 1 2 3 4  

1.5.sub

sub(repl, string[, count]) | re.sub(pattern, repl, string[, count]):
使用repl替换string中每一个匹配的子串后返回替换后的字符串。 
当repl是一个字符串时,可以使用\id或\g<id>、\g<name>引用分组,但不能使用编号0。 
当repl是一个方法时,这个方法应当只接受一个参数(Match对象),并返回一个字符串用于替换(返回的字符串中不能再引用分组)。 
count用于指定最多替换次数,不指定时全部替换。

[python]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. import re  
  2.    
  3. p = re.compile(r'(\w+) (\w+)')  
  4. s = 'i say, hello world!'  
  5.    
  6. print p.sub(r'\2 \1', s)  
  7.    
  8. def func(m):  
  9.     return m.group(1).title() + ' ' + m.group(2).title()  
  10.    
  11. print p.sub(func, s)  
  12.    
  13. ### output ###  
  14. # say i, world hello!  
  15. # I Say, Hello World!  

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值