python - 将字符串转换为列表的正则表达式(Python)

标签 python regex string list

程序输出包含以下格式行的文件

{Foo} Bar Bacon {Egg}

其中 FooEgg 可以(但不一定)由多个单词组成。 BarBacon 始终是一个单词。

我需要在变量中获取Bar以用于我的进一步代码。我想如果我在匹配的正则表达式处分割刺痛,这会起作用。这将返回四个元素的列表,因此我可以使用 list[1] 轻松取出第二个元素。

我该如何编写这样的正则表达式?

我需要将字符串拆分为单个空格' ,但前提是该单个空格没有被大括号中的文本包围。

\s(?=[a-zA-Z{}]) 为我提供了所有空格,因此其行为与 ' ' 完全相同。如何排除花括号中的空格?

最佳答案

您可以尝试{[^}]*}\s(\w+)

>>> import re
>>> print re.search(r'{[^}]*}\s(\w+)', '{Foo} Bar Bacon {Egg}').group(1)
Bar

Demo

说明:

  • {[^}]*} 首先匹配大括号内的第一部分
  • \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.

https://docs.python.org/3/library/re.html#re.search

关于python - 将字符串转换为列表的正则表达式(Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49140120/

相关文章:

带空格的 Java 字符串填充

python - 如何用冒号解析时区

c++ - STL中使用了哪种字符串匹配算法?

python - Pandas 根据分组列值合并 DF 列表

regex - 用文字替换换行符\n

python - 对于每个测试用例,显示完成计划所需的最少天数。算法思想?

正则表达式匹配 R 中重复三次或多次的任何字符

php - ABAB 中的正则表达式匹配数(必须相同)

python - Scikit 学习(Python): what does f_regression() compute?

python - 如何找到哪些单元格无法转换为 float ?