在python3上用Regex提取子字符串

2024-05-15 17:40:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用正则表达式提取一个子字符串

这是我的剧本:

import re
_text = "sdiskpart(device='D:\\', mountpoint='D:\\', fstype='FAT32', opts='rw,fixed')"
print(re.findall("device=(\\'.*\\')", _text))

我试图得到device的值,在这个字符串中是“D:\”

如您所见,我用REgex尝试了“device=(\'.*\')”,它返回:

["'D:\', mountpoint='D:\', fstype='FAT32', opts='rw,fixed'"]

我对REgex不专业,我怎么能强迫它取D:\并打印出来呢?在


Tags: 字符串textimportredeviceregexfixedrw
2条回答

参考https://docs.python.org/3/library/re.html

>>> print(re.findall("device=(\\'[A-Z]:\\\\')", _text))
["'D:\\'"]

您可能需要将*替换为[A-Z]。我想驱动器号是大写的,否则就用[A-Za-z]

您可以使用非紧急regexp

import re

print( re.findall("device='(.*?)'", _text))

注意到了吗?意思是“不急着”,所以它需要最少的字符,直到下一个'。。。在

相关问题 更多 >