我正在使用python 3并尝试使用netstat -nb获取进程的名称。 我设法在子进程中使用了以下字符串:
'TCP 192.168.1.22:65477 212.55.188.116:443已建立\ n [WinStore.App.exe]'
我的问题是,如何使用正则表达式获取进程“ WinStore.App.exe”的名称。
答案 0 :(得分:1)
您可以使用
\[([^\[\]]+)\]
并使用第一组。参见a demo on regex101.com。
Python
中:
import re
string = ' TCP 192.168.1.22:65477 212.55.188.116:443 ESTABLISHED\n [WinStore.App.exe]'
rx = re.compile(r'\[([^\[\]]+)\]')
apps = [m.group(1) for m in rx.finditer(string)]
print(apps)
这产生
['WinStore.App.exe']
答案 1 :(得分:0)
答案 2 :(得分:0)
这是一种方法。它假定您的输入字符串中没有〜字符,并且在方括号之前假定不超过200个字符,在方括号中假定不超过99个字符,并且在方括号之后不超过200个字符
str = ' TCP 192.168.1.22:65477 212.55.188.116:443 ESTABLISHED\n [WinStore.App.exe]'
newstr = re.sub("^[^~]{0,200}\[([^~]{0,99})\][^~]{0,200}$" , r"\1", str )