我试图用正则表达式抓住括号外的任何文本.
示例字符串
Josie Smith [3996 COLLEGE AVENUE,SOMETOWN,MD 21003] Mugsy Dog Smith [2560 OAK ST,GLENMEADE,WI 14098]
我能够成功地获得方括号内的文本:
addrs = re.findall(r"\[(.*?)\]", example_str)
print addrs
[u'3996 COLLEGE AVENUE, SOMETOWN, MD 21003',u'2560 OAK ST, GLENMEADE, WI 14098']
Run Code Online (Sandbox Code Playgroud)
但我在方括号之外得到任何东西都遇到了麻烦.我尝试过以下内容:
names = re.findall(r"(.*?)\[.*\]+", example_str)
Run Code Online (Sandbox Code Playgroud)
但是只找到第一个名字:
print names
[u'Josie Smith ']
Run Code Online (Sandbox Code Playgroud)
到目前为止,我只看到一个包含一到两个name [address]组合的字符串,但我假设字符串中可以有任意数量的字符串.
如果没有嵌套括号,您可以这样做:
re.findall(r'(.*?)\[.*?\]', example_str)
Run Code Online (Sandbox Code Playgroud)
但是,你甚至不需要这里的正则表达式.只是在括号上分开:
(s.split(']')[-1] for s in example_str.split('['))
Run Code Online (Sandbox Code Playgroud)
您尝试不起作用的唯一原因:
re.findall(r"(.*?)\[.*\]+", example_str)
Run Code Online (Sandbox Code Playgroud)
...就是你在括号内做了一个非贪婪的匹配,这意味着它捕获了从第一个开放括号到最后一个关闭括号的所有内容,而不是只捕获第一对括号.
Also, the + on the end seems wrong. If you had 'abc [def][ghi] jkl[mno]', would you want to get back ['abc ', '', ' jkl'], or ['abc ', ' jkl']? If the former, don't add the +. If it's the latter, do—but then you need to put the whole bracketed pattern in a non-capturing group: r'(.*?)(?:\[.*?\])+.
If there might be additional text after the last bracket, the split method will work fine, or you could use re.split instead of re.findall… but if you want to adjust your original regex to work with that, you can.
In English, what you want is any (non-greedy) substring before a bracket-enclosed substring or the end of the string, right?
所以,你需要\[.*?\]和之间的交替$.当然,您需要将其分组才能编写替换,并且您不想捕获该组.所以:
re.findall(r"(.*?)(?:\[.*?\]|$)", example_str)
Run Code Online (Sandbox Code Playgroud)
如果从未嵌套括号:
([^[\]]+)(?:$|\[)
Run Code Online (Sandbox Code Playgroud)
例:
>>> import re
>>> s = 'Josie Smith [3996 COLLEGE AVENUE, SOMETOWN, MD 21003]Mugsy Dog Smith [2560 OAK ST, GLENMEADE, WI 14098]'
>>> re.findall(r'([^[\]]+)(?:$|\[)', s)
['Josie Smith ', 'Mugsy Dog Smith ']
Run Code Online (Sandbox Code Playgroud)
说明:
([^[\]]+) # match one or more characters that are not '[' or ']' and place in group 1
(?:$|\[) # match either a '[' or at the end of the string, do not capture
Run Code Online (Sandbox Code Playgroud)