Python 找到特定的字符串,然后在其后面复制单词并将其连接到变量

Python 找到特定的字符串,然后在其后面复制单词并将其连接到变量,python,python-2.7,Python,Python 2.7,假设我运行一个命令~#/testapp.sh或例如linux命令~#dmesg,并且此示例命令中的任何一个都会在linux终端中打印以下行: -随机长线---长线---- 尺寸:12 mydata:0x5b mydata:0xa8 mydata:0xcc mydata:0x18 mydata:0x15 mydata:0x18 --随机线-- 然后,我想在“0x”之后搜索all关键字,将这些变量(例如:5b、a8、cc)连接起来并作为字符串存储在名为test_variable的字符串变量中。tes

假设我运行一个命令~#/testapp.sh或例如linux命令~#dmesg,并且此示例命令中的任何一个都会在linux终端中打印以下行:

-随机长线---长线----
尺寸:12
mydata:0x5b
mydata:0xa8
mydata:0xcc
mydata:0x18
mydata:0x15
mydata:0x18 --随机线--

然后,我想在“0x”之后搜索all关键字,将这些变量(例如:5b、a8、cc)连接起来并作为字符串存储在名为test_variable的字符串变量中。test_变量的内容应该类似于“5ba8cc181518”。我想在Python2.7中实现这一点

以下是我的尝试代码:

import sys
import os
import re
import time
import string

test_variable = ""
test_variable = re.findall(r' bx(\W)',os.system("dmesg")) 
test_variable += test_variable
print "content is : " + test_variables

您可以尝试以下非正则表达式解决方案:

sample = os.popen('dmesg').read()

# Sample
sample = """
-random long line ---long line----
size of : 12
mydata : 0x5b
mydata : 0xa8
mydata : 0xcc
mydata : 0x18
mydata : 0x15
mydata : 0x18 --random line--
"""

concat_out = ''.join([word.replace("0x","") 
                      for word in sample.split()
                      if word.startswith("0x")])
print(concat_out)
要获取“5ba8cc181518”,findall()将返回一个列表,而不是字符串。要将其转换为字符串,请使用:

''.join(re.findall(...))
对于正则表达式,我建议如下:

matches = re.findall(r'mydata\s*\:\s*0x([0-9a-f]{2})', sample_data, re.IGNORECASE)
test_variable = ''.join(matches)
它对什么是有效代码有一点限制

如果您完全确定“0x”保证能够识别代码,并且不会出现在其他任何地方,则可以将其简化为:

matches = re.findall(r'0x([0-9a-f]{2})', sample_data, re.IGNORECASE)
本质上,这个正则表达式查找“0x”,后跟两个十六进制数字。

os.system('dmesg')
仅在执行
dmesg
后返回

您更希望以这种方式使用模块:

import re
import subprocess

test_variable = subprocess.check_output('dmesg',shell=True)
result = ''.join(re.findall(r'0x([0-9a-f]{2}', test_variable))

简单地调用os.system不会捕获输出。