How do I find the string between two special characters?

送分小仙女□ 提交于 2019-12-17 20:04:20

问题


For example, I need everything in between the two square brackets. File1

[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.


回答1:


Regular expressions are the most flexible option.

For another approach, you can try string's partition and rpartition methods:

>>> s = "[virus 1 [isolated from china]]"
>>> s.partition('[')[-1].rpartition(']')[0]
'virus 1 [isolated from china]'



回答2:


You can use a greedy regex:

re.search(r'\[(.*)\]', your_string).group(1)



回答3:


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 strip in 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.)



来源:https://stackoverflow.com/questions/14716342/how-do-i-find-the-string-between-two-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!