Skip to content Skip to sidebar Skip to footer

Substring In Python

i have strings with Following pattern in python : 2011-03-01 14:10:43 C:\Scan\raisoax.exe detected Trojan.Win32.VBKrypt.agqw how get substrings: C:\Scan\raisoax.exe and Tro

Solution 1:

just use the substring method of a python String.

s = r"2011-03-01 14:10:43 C:\Scan\raisoax.exe detected    Trojan.Win32.VBKrypt.agqw"
s.split("\t")

gets you

['2011-03-01 14:10:43 C:\\\\Scan\\raisoax.exe detected', 'Trojan.Win32.VBKrypt.agqw']

Solution 2:

A solution using regexes:

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()

This will catch files with spaces in them as well. It will fail if you have files with " detected " in them. (you can add a forward assertion to fix that as well.

Solution 3:

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.agqwprint v[-3] # gives you C:\Scan\raisoax.exe

To handle spaces in filenames try

print" ".join(v[2:-2])

Solution 4:

Use the re package. Something like

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)

Solution 5:

You can use this package called "substring". Just type "pip install substring". You can get the substring by just mentioning the start and end characters/indices.

Post a Comment for "Substring In Python"