Python 如何找到两个特殊字符之间的字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14716342/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find the string between two special characters?
提问by Lord Voldemort
For example, I need everything in between the two square brackets. File1
例如,我需要两个方括号之间的所有内容。文件 1
[Home sapiens]
[Mus musculus 1]
[virus 1 [isolated from china]]
So considering the above example, I need everything in between the first and last square brackets.
所以考虑到上面的例子,我需要第一个和最后一个方括号之间的所有内容。
采纳答案by orip
Regular expressions are the most flexible option.
正则表达式是最灵活的选项。
For another approach, you can try string's partitionand rpartitionmethods:
对于另一种方法,您可以尝试使用 string 的partition和rpartition方法:
>>> s = "[virus 1 [isolated from china]]"
>>> s.partition('[')[-1].rpartition(']')[0]
'virus 1 [isolated from china]'
回答by Blender
You can use a greedy regex:
您可以使用贪婪的正则表达式:
re.search(r'\[(.*)\]', your_string).group(1)
回答by abarnert
Given your sample input, it looks like every line begins and ends with brackets. In which case, forget regexps, this is trivial:
鉴于您的示例输入,看起来每一行都以括号开头和结尾。在这种情况下,忘记正则表达式,这是微不足道的:
for line in whatever:
contents = line.strip()[1:-1]
(I've added the stripin case your line source is leaving the newlines in, or there are invisible spaces after the closing bracket in your input. If it's not necessary, leave it out.)
(我添加了strip以防您的行源保留换行符,或者输入中的右括号后有不可见的空格。如果没有必要,请将其省略。)

