- 论坛徽章:
- 0
|
没有递归的Python正则好纠结~
我使用堆栈的方式解的。代码如下。- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- #
- #author: rex
- #blog: http://iregex.org
- #filename x.py
- #created: 2010-11-01 18:25
- s='''pig<asdf <123> <abc> <1 <1> > > , <asdf>, <1234>'''
- def sharp(s):
- stack=0
- result=[]
- for i in s:
- if stack==0 and i != '<':
- continue
- elif stack==0 and i=='<':
- stack = 1
- result.append(i)
- elif stack==1 and i == '>':
- result.append(i)
- return "".join(result)
- elif stack>0 and i=='>':
- result.append(i)
- stack -= 1
- elif stack>0 and i=='<':
- result.append(i)
- stack += 1
- elif stack >0 and i not in ('>','<'):
- result.append(i)
- def all(s):
- while True:
- result=sharp(s)
- if result:
- print result
- index=s.find(result)
- s=s[index+len(result):]
- else:
- break
-
- all(s)
复制代码 结果如下:- <asdf <123> <abc> <1 <1> > >
- <asdf>
- <1234>
复制代码 |
|