我有以下字符串(文件):

s = '''
\newcommand{\commandName1}{This is first command}

\newcommand{\commandName2}{This is second command with {} brackets inside
in multiple lines {} {}
}

\newcommand{\commandName3}{This is third, last command}

'''

现在我想使用Pythonre包将数据提取到字典中,其中key是命令名(\commandName1\commandName2\commandName3),值是This is first commandThis is second command with {} brackets inside in multiple lines {} {}This is third, last command.我试了一下,比如:

re.findall(r'\\newcommand{(.+)}{(.+)}', s)

但它不起作用,因为第二个指挥部里面有{}个.要做到这一点,最简单的方法是什么?

推荐答案

您可以使用此正则表达式:

(?s)\\newcommand{([^}]+)}{(.+?)}(?=\s*(?:\\newcommand|$))

RegEx Demo

Code Demo

RegEx Breakdown:

  • (?s):启用DOTALL(单线)模式
  • \\newcommand:
  • {:匹配{
  • ([^}]+):匹配捕获组#1中不是{的任何字符中的1+
  • }:匹配}
  • {:匹配{
  • (.+?):匹配捕获组#2中任何字符的1+
  • }:匹配}
  • (?=\s*(?:\\newcommand|$)):向前看以断言存在0个或更多空格和\newcommand,否则将结束输入.

Code:

import re

s = r'''
\newcommand{\commandName1}{This is first command}

\newcommand{\commandName2}{This is second command with {} brackets inside
in multiple lines {} {}
}

\newcommand{\commandName3}{This is third, last command}
'''

print (re.findall(r'(?s)\\newcommand{([^}]+)}{(.+?)}(?=\s*(?:\\newcommand|$))', s))

Python-3.x相关问答推荐

使用魔方无法从图像中识别单个字符

根据样本量随机 Select 组内样本

pandas查找另一列中是否存在ID

如何在输入正确的用户名和密码时添加按钮?

将数据帧扩展为矩阵索引

我用Kivy创建的应用程序在安卓系统上运行时出错.(attributeerror:';class';对象没有属性';_javaclass__cls_storage';)

将数据框中的值与另一个数据框中的多列进行比较,以获取条目以有效方式匹配的列表列表

将 pandas Timestamp() 转换为 datetime.datetime() 以支持 peewee DateTimeField()

为什么 return node.next 会返回整个链表?

通过附加/包含多个列表来创建 nDimensional 列表

为什么 f-strings 比 str() 更快地解析值?

使用带有多线程的 win32com

如何将具有多个参数的函数传递给 python concurrent.futures.ProcessPoolExecutor.map()?

Pythonic,自定义警告

Python:如何判断一个项目是否被添加到一个集合中,没有 2x(hash,lookup)

使用 distutils 分发预编译的 python 扩展模块

str.format_map(mapping) 和 str.format 有什么区别

Python3 - 如何从现有抽象类定义抽象子类?

SQLAlchemy:如果不存在则创建模式

同步调用协程