程序输出包含以下格式行的文件
{Foo} Bar Bacon {Egg}
其中 Foo
和 Egg
可以(但不一定)由多个单词组成。 Bar
和 Bacon
始终是一个单词。
我需要在变量中获取Bar
以用于我的进一步代码。我想如果我在匹配的正则表达式处分割刺痛,这会起作用。这将返回四个元素的列表,因此我可以使用 list[1]
轻松取出第二个元素。
我该如何编写这样的正则表达式?
我需要将字符串拆分为单个空格'
,但前提是该单个空格没有被大括号中的文本包围。
\s(?=[a-zA-Z{}])
为我提供了所有空格,因此其行为与 ' '
完全相同。如何排除花括号中的空格?
最佳答案
您可以尝试{[^}]*}\s(\w+)
>>> import re
>>> print re.search(r'{[^}]*}\s(\w+)', '{Foo} Bar Bacon {Egg}').group(1)
Bar
说明:
{[^}]*}
首先匹配大括号内的第一部分\s
然后是空格(\w+)
然后是第二部分;您将其放入捕获组中,因此它可以在搜索结果中显示为group(1)
re.search(pattern, string, flags=0)
Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding match object. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.
关于python - 将字符串转换为列表的正则表达式(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49140120/