[英]Python regex match issue and grouping multiple groups
I am trying to parse a command output, which looks like: 我试图解析一个命令输出,看起来像:
2.437 GHz (Channel 6)
Quality=39/70 Signal level=-71 dBm
Encryption key:on
ESSID:"testssid"
IE: IEEE 802.11i/WPA2 Version 1
IE: WPA Version 1
..and essentially convert it to: ..并基本上将其转换为:
channel = 6
quality = "39/70"
signal = -71
encryption = true
essid = "testssid"
wpa = true
I am not particularly good with regular expressions but here's my attempt at extracting these fields: 我对正则表达式并不是特别擅长,但这是我尝试提取这些字段:
m = re.search('Channel (.+)\)', n)
if m:
print m.group(1)
m = re.search('Quality\=(.{5})', n)
if m:
print m.group(1)
m = re.search('level\=(.+)', n)
if m:
print m.group(1)
m = re.search('key\:(.+)', n)
if m:
print m.group(1)
m = re.search('ESSID\:\"(.+?)\"', n)
if m:
print m.group(1)
This outputs: 这输出:
6
39/70
-71 dBm
off
testssid
There are two problems: First one is the 'Quality' value, as I have a hardcoded value that might break if the match is shorter than 5 characters and the second one is the 'signal value', which I rather have without the "dBM" portion. 有两个问题:第一个是'质量'值,因为我有一个硬编码值,如果匹配短于5个字符可能会破坏,第二个是'信号值',我宁愿没有“dBM” “部分。 I guess in both cases I'd like to match until the next whitespace character, couldn't get it working with
\\s
though. 我想在这两种情况下我都希望匹配到下一个空格字符,但是不能让它与
\\s
一起工作。
Also, having a few re.search
operations look cluttered and messy, is there a way to combine these or tidy it up generally? 此外,有一些
re.search
操作看起来混乱和混乱,有没有办法将这些结合起来或整理一下?
Thanks. 谢谢。
re.search('Quality\=(\d+/\d+)', n) #matches a number a slash and a number #/#
re.search('level\=([+-]?\d+)', n) #matches 1 or more numbers so ignore dbm
to clean it up you could do 你可以做的清理它
patterns = {'quality':'Quality\=(\d+/\d+)',
'level': 'level\=([+-]?\d+)',
'key':'key\:(.+)',
'channel':'Channel (.+)\)'}
body_of_text = open("somefile.txt").read()
results = dict([(key,re.search(regex,body_of_text).group(1)) for key,regex in patterns.items()])
print results
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.