0

正規表現を使用して、Python の文字列から次のテキストを削除する方法を知りたいと思っていました。

string = "Hello (John)"
(magic regex)
string = "Hello "

ただし、部分文字列「John」が含まれている場合にのみ、括弧内のテキストを削除したいと考えています。たとえば、

string = "Hello (Sally)"
(magic regex)
string = "Hello (Sally)"

これは可能ですか?ありがとう!

4

3 に答える 3

1
import re
REGEX = re.compile(r'\(([^)]+)\)')

def replace(match):
    if 'John' in match.groups()[0]:
        return ''
    return '(' + match.groups()[0] + ')'

my_string = 'Hello (John)'
print REGEX.sub(replace, my_string)
my_string = 'Hello (test John string)'
print REGEX.sub(replace, my_string)
my_string = 'Hello (Sally)'
print REGEX.sub(replace, my_string)

Hello 
Hello 
Hello (Sally)
于 2013-10-20T19:50:04.523 に答える