Regex帮助Python?

2024-03-28 23:09:36 发布

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

我有这个密码:

import re
#TEST CASES
match_dict = ['hello(here)',
             'Hello   (Hi)',
             "'dfsfds Hello (Hi) fdfd' Hello (Yes)",
             "Hello ('hi)xx')",
             "Hello  ('Hi')"]
for s in match_dict:
    print "INPUT: %s" % s
    m = re.sub(r"(?<!\()'[^']+'", '', s, flags=re.M)
    paren_quotes = re.findall(r"Hello\s*\('([^']+)'\)", m, flags=re.M)
    output = paren_quotes if paren_quotes else []
    m = re.sub(r"Hello\s*\('[^']+'\)", '', m, flags=re.M)
    paren_matches = re.findall(r"Hello\s*\(([^)]+)\)", m, flags=re.M)
    if paren_matches:
        output.extend(paren_matches)
    print 'OUTPUT: %s\n' % output

这段代码用来输出单词“Hello”后面括号中的所有内容

Hello (Hi)  would give 'Hi'

我的问题是当我输入:

Hello('Hi')    

…当我希望它返回"'Hi'"时,它仍然返回'Hi'

有人知道我如何修复这个代码吗?你知道吗


Tags: 代码re密码hellooutputifmatchhi
2条回答

只需使用非贪婪匹配:

matches = re.search(r'^Hello\s*\((.*?)\)', text)
>>> import re
>>> p = re.compile(r'Hello\s*\((.*?)\)', re.M)
>>> m = p.findall("Hello  ('Hi')")
>>> print m
["'Hi'"]
>>> m = p.findall("'dfsfds Hello (Hi) fdfd' Hello (Yes)")
>>> print m
['Hi', 'Yes']

相关问题 更多 >