[英]Python - How to use regex to find a text?
Please bear with me, I'm new in Python.请耐心等待,我是 Python 新手。 I have a text, and I want to get the value after ^s
until the next ^
so for example there's ^s100^
then the value is 100
.我有一个文本,我想在^s
之后获得值,直到下一个^
所以例如有^s100^
那么值是100
。 This is what I've tried so far:这是我迄今为止尝试过的:
#!/usr/bin/python
import re
text="^request^ #13#10#13#10^s100^GET http://facebook.com #13#10Host: http://facebook.com #13#10X-Online-Host: http://facebook.com #13#10X-Forward-Host: http://facebook.com #13#10Connection: Keep-Alive#13#10#13#10"
if re.split(r'\^s',text):
print "found it"
The problem is that it always returns found it
even if I change the regex to re.split(r'\\^bla',text)
and basically any text, it will always return found it
Please help me to fix it.问题是它总是返回found it
即使我将正则表达式更改为re.split(r'\\^bla',text)
和基本上任何文本,它总是会返回found it
请帮我修复它。
What you probably want is re.search
:你可能想要的是re.search
:
import re
text="^request^ #13#10#13#10^s100^GET http://facebook.com #13#10Host: http://facebook.com #13#10X-Online-Host: http://facebook.com #13#10X-Forward-Host: http://facebook.com #13#10Connection: Keep-Alive#13#10#13#10"
m = re.search(r'\^s(.*)\^',text)
print m.group(1) # 100
You don't need as much code, try the following:您不需要那么多代码,请尝试以下操作:
import re
text = "^request^ #13#10#13#10^s100^GET http://facebook.com #13#10Host: http://facebook.com #13#10X-Online-Host: http://facebook.com #13#10X-Forward-Host: http://facebook.com #13#10Connection: Keep-Alive#13#10#13#10"
match = re.search(r"\^s(\d+)\^", text)
if match:
print match.group(1)
Regex Explanation:正则表达式说明:
\^s(\d+)\^
Match the character “^” literally «\^»
Match the character “s” literally (case sensitive) «s»
Match the regex below and capture its match into backreference number 1 «(\d+)»
Match a single character that is a “digit” (ASCII 0–9 only) «\d+»
Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+»
Match the character “^” literally «\^»
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.