简体   繁体   中英

Remove text from brackets if certain word exist inside brackets in python

I have a sample string

s='((Xyz_lk) some stuff (XYZ_l)) (vbc vb XyZ vc))'
s = '((Xyz_lk) some stuff (XYZ_l)) (XyZ vc))'
s = '((Xyz_lk) some stuff (XYZ_l)) (vc XyZ))'

if XyZ appear anywhere inside the brackets starting, ending then remove text within that parenthesis

output  ='((Xyz_lk) some stuff (XYZ_l)))'

How could I do it in the easiest possible way in Python? Maybe by using RegEx (which I am not good at)?

You can do

re.sub(r"\s*\((\w|\s)*(xyz|XyZ)(\w|\s)*\)", "", s)

Result

'((Xyz_lk) some stuff (XYZ_l)))'

The regex \s*\((\w|\s)*(xyz|XyZ)(\w|\s)*\) is getting any whitespace character followed by ( followed by any whitespace character zero or more or word character zero or more than the XyZ pattern and again any whitespace character zero or more or word character zero or more followed by )

You can simply do this.

1> Check weather the required string (XyZ) is in given string.

2> After getting the location find the location of the parenthesis surrounding that string.

3> Skip that part of string in output string.

s='((Xyz_lk) some stuff (XYZ_l)) (vbc vb XyZ vc))'

if "XyZ" in s:
    index = s.index("XyZ")

i = j = index   

while s[i] != "(":
    i -= 1

while s[j] != ")":
    j += 1

output = (s[ :i] + s[j+1:])
print(output)

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