问题,给出一个字符串和模式,如何得到该串中所有符合模式的所有子串?
一直以为bash下有比较简单的解决方法,结果翻了半天资料,发现bash没有很好的解决方法;awk倒是提供了match函数,但是只能做贪婪匹配,是它的局限性。用python能轻松解决这个问题:
[chenjian@localhost bashprogram]$ python
Python 2.4.3 (#1, Jun 13 2006, 11:46:08)
[GCC 4.1.1 20060525 (Red Hat 4.1.1-1)] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> import re
>>> re.findall(r’blade.*end’, “aaaaa blade asdfasdf endsdafsadfasdflkuimasdfbladeasdfsadfasdfuewfasdf,n!adsjfasdfendasdflkjasdfulka;dsjfh”)
[‘blade asdfasdf endsdafsadfasdflkuimasdfbladeasdfsadfasdfuewfasdf,n!adsjfasdfend’]
>>> re.findall(r’blade.*?end’, “aaaaa blade asdfasdf endsdafsadfasdflkuimasdfbladeasdfsadfasdfuewfasdf,n!adsjfasdfendasdflkjasdfulka;dsjfh”)
[‘blade asdfasdf end’, ‘bladeasdfsadfasdfuewfasdf,n!adsjfasdfend’]

要点:
1。“.*”和“.*?”的区别
前者是贪婪的
后者是非贪婪的

note by (2013/10/02):

  1. shell:其实我一直没有抛弃你,直到2013/10/02仍然使用
  2. python:其实我一直在暗恋你
Advertisements