Reputation: 2582
I'm trying to extract a substring with Regex,
Here is my script:
import re
_text = "sdiskpart(device='D:\\', mountpoint='D:\\', fstype='FAT32', opts='rw,fixed')"
print(re.findall("device=(\\'.*\\')", _text))
I'm trying to get the value of device, in this string it's "D:\"
as u can see I tried "device=(\'.*\')" with REgex and it returned:
["'D:\', mountpoint='D:\', fstype='FAT32', opts='rw,fixed'"]
I'm not professional on REgex, How can I force it to take D:\ and print it out ?
Upvotes: 0
Views: 5507
Reputation: 8066
You can use non-eager regexp
import re
print( re.findall("device='(.*?)'", _text))
notice that the .*? means non-eager so it will take the least chars until the next ' ...
Upvotes: 4
Reputation: 916
REFER https://docs.python.org/3/library/re.html
>>> print(re.findall("device=(\\'[A-Z]:\\\\')", _text))
["'D:\\'"]
You might have to replace * with [A-Z]. I think the drive letter are in caps always else use[A-Za-z]
Upvotes: 2