如何查找symols #TR=
后面的所有内容,并使用re模块在[ ]
的内部。例如#TR=[ dfgg dfgddfg dgfgf dgdgdg dfgfg ]
Python。正则表达式
0
A
回答
5
import re
txt = '#TR=[ dfgg ] a kuku #TR=[ala ma kota]'
如果你要搜索只是这种模式的第一次出现,使用方法:
matches = re.search('#TR=\[([^\]]*)\]', txt)
if matches:
print(repr(matches.group(1)))
' dfgg dfg '
如果你想查找的文字,使用的所有事件:
matches = re.findall('#TR=\[([^\]]*)\]', txt)
if matches:
print(matches)
[' dfgg ', 'ala ma kota']
请记住检查您正在搜索的字符是否在正则表达式中有special meaning(如[
或]
)。如果它们是特殊的,请用反斜杠将它们转义出来:\[
。
另外请记住,默认情况下,正则表达式是“贪婪”,这意味着他们尝试获得尽可能多的文本以匹配模式;所以,如果你使用.*
(意思是“匹配任何字符除了换行符” details)而不是[^\]]*
(意思是“比赛直到]
被发现,和之前停止”),太多的文字可以匹配:
matches = re.findall('#TR=\[(.*)\]', txt)
if matches:
print(matches)
[' dfgg ] a kuku #TR=[ala ma kota']
您也可以使用“非贪婪”修改?
在你的模式,这使的“少字符 - 越好的”匹配(使用*?
,+?
)限定符(*
,+
)之后。其结果可能是更具可读性:代替
'#TR=\[(.*?)\]'
:
'#TR=\[([^\]]*)\]'
有一个伟大的在线工具测试图案作为你型:RegExr by Grant Skinner。
0
(?< =#TR = [)[^] *(?=])
1
import re
# compile the regex
exp = re.compile('.*\[(.*)\].*')
txt = r"#TR=[ dfgg dfgddfg dgfgf dgdgdg dfgfg ]"
match = exp.match(txt)
# grab the text between the square brackets
result = match.group(1)
+0
对不起,我错误地编辑了你的答案,意在编辑我自己的答案。恢复了我的改变。 – 2010-11-24 22:32:49
相关问题
- 1. 正则表达式正则表达式正则表达式使用正则表达式,但不是与Python
- 2. 正则表达式python表达式
- 3. Python的正则表达式:“喜欢”正则表达式模式?
- 4. Python Unicode正则表达式
- 5. Python和正则表达式
- 6. 正则表达式或Python
- 7. Python正则表达式Findall
- 8. Python - 正则表达式dir
- 9. python re.sub正则表达式
- 10. Python正则表达式
- 11. 正则表达式python 3.4
- 12. Python正则表达式子
- 13. Python的正则表达式?
- 14. python正则表达式appengine
- 15. 正则表达式在Python
- 16. Python的正则表达式
- 17. 在python正则表达式
- 18. Python的正则表达式
- 19. 正则表达式python
- 20. Python 3.3正则表达式?
- 21. 正则表达式在Python
- 22. Python的正则表达式
- 23. Python正则表达式
- 24. Python正则表达式
- 25. Python的正则表达式{
- 26. Python正则表达式findall
- 27. Python findall正则表达式
- 28. Python正则表达式
- 29. IPv6正则表达式python
- 30. Python的正则表达式
您是否期待在顶层`[]`内嵌套`[]`? – martineno 2010-11-24 22:30:39