如何在其他文本之间抓取特定文本?

时间:2019-04-30 00:43:40

标签: python

我需要帮助从此字符串中仅抓取K334-76A9:

b'\x0cWelcome, Pepo \r\nToday is Mon 04/29/2019 \r\n\r\n Volume in drive C has no label.\r\n Volume Serial Number is K334-76A9\r\n

请帮忙,我尝试了很多事情,但都没有成功。 抱歉,如果我的问题不好:/

2 个答案:

答案 0 :(得分:3)

如果要查找格式xxxx-xxxx,无论您使用什么字符串,都可以这样操作:

import re

b = '\x0cWelcome, Pepo \r\nToday is Mon 04/29/2019 \r\n\r\n Volume in drive C has no label.\r\n Volume Serial Number is K334-76A9\r\n'

splitString = []
splitString = b.split()

r = re.compile('.{4}-.{4}')

for string in splitString:
    if r.match(string):
        print(string)

输出:

K334-76A9

答案 1 :(得分:1)

这里的代码可以抓取“序列号为”后到下一个空白字符的所有内容。

import re

data = b'\x0cWelcome, Pepo \r\nToday is Mon 04/29/2019 \r\n\r\n Volume in drive C has no label.\r\n Volume Serial Number is K334-76A9\r\n'

pat = re.compile(r"Serial Number is ([^\s]+)")
match = pat.search(data.decode("ASCII"))
if match:
    print(match.group(1))

结果:

K334-76A9

您可以根据需要调整正则表达式。正则表达式是Da Bomb!这真的很简单,但是您可以使用它们来完成复杂的事情。

相关问题