[英]substring in python
我在python中有以下模式的字符串:
2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw
如何獲取子字符串:C:\\ Scan \\ raisoax.exe和Trojan.Win32.VBKrypt.agqw
字符串之間是制表符
只需使用python String的substring方法即可。
s = r"2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw"
s.split("\t")
讓你
['2011-03-01 14:10:43 C:\\\\Scan\\raisoax.exe detected', 'Trojan.Win32.VBKrypt.agqw']
使用正則表達式的解決方案:
s = "2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw"
reg = re.match(r"\S*\s\S*\s(.*)[^\ ] detected\s+(.*)",s)
file,name = reg.groups()
這還將捕獲其中包含空格的文件。 如果其中包含“檢測到”的文件,它將失敗。 (您也可以添加前向斷言來解決該問題。
s = r"2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw"
v = s.split()
print v[-1] # gives you Trojan.Win32.VBKrypt.agqw
print v[-3] # gives you C:\Scan\raisoax.exe
要處理文件名中的空格,請嘗試
print " ".join(v[2:-2])
使用重新包裝。 就像是
import re
s = r'2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw'
m = re.search('\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}\s(.+)\s+detected\s+(.+)', s)
print 'file: ' + m.group(1)
print 'error: ' + m.group(2)
您可以使用稱為“子字符串”的程序包。 只需輸入“ pip install substring”。 您只需提及開始和結束字符/索引即可獲得子字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.