简体   繁体   中英

Regex to search for a pattern and replace the pattern and sub-string preceding it

I am new to python. I have a string from which I would like to select pattern false and the characters preceding it until hyphen with some other string if required.

Example:

string = -I false -n 0 -i false -X false -E 0 --min-repeat-size 5 --min-repeat-entropy 0 --no-partial-observations false -u false

Result string should be like this:

string = -n 0 -E 0 --min-repeat-size 5 --min-repeat-entropy 0 

I use re method to replace false with another character but could not get what I wanted.

>>> import re
>>> 
>>> string = "-I false -n 0 -i false -X false -E 0 --min-repeat-size 5 --min-repeat-entropy 0 --no-partial-observations false -u false"
>>> 
>>> string = re.sub(r"-{1,2}[\w-]+\s+false\s?", "", string)
>>> 
>>> string
'-n 0 -E 0 --min-repeat-size 5 --min-repeat-entropy 0 '
>>> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM