Python 用于在特定节中查找文本的正则表达式
我有一个正则表达式问题。我的数据如下:Python 用于在特定节中查找文本的正则表达式,python,regex,Python,Regex,我有一个正则表达式问题。我的数据如下: [Section 1] title = RegEx name = Joe color = blue [Section 2] height = 101 name = Gray 我的问题是,我是否可以编写一个正则表达式来捕获[第1节]中的'name'键?本质上,捕获可能存在于多个位置的密钥,但仅从特定部分捕获。我将用python实现这一点。 谢谢使用ConfigParser非常简单,但您需要将数据格式更改为: config_fi
[Section 1]
title = RegEx
name = Joe
color = blue
[Section 2]
height = 101
name = Gray
我的问题是,我是否可以编写一个正则表达式来捕获[第1节]中的'name'键?本质上,捕获可能存在于多个位置的密钥,但仅从特定部分捕获。我将用python实现这一点。
谢谢使用ConfigParser非常简单,但您需要将数据格式更改为: config_file.cfg
[Section 1]
title: RegEx
name: Joe
color: blue
[Section 2]
height: 101
name: Gray
test_config.py
import ConfigParser
def get_config(section, prop_file_path):
config = ConfigParser.ConfigParser()
config.read(prop_file_path)
options = config.options(section)
data = {}
for option in options:
try:
data[option] = config.get(section, option)
except:
data[option] = None
raise Exception("exception on %s!" % option)
return data
data = get_config("Section 1", "path/to/file/config_file.cfg")
print data['name']
虽然我不会对正则表达式这样做,因为你问:
\[Section 1\][^[]*name\s*=\s*(.*)
[^[]
位可防止正则表达式过于贪婪,与指定节外的“名称”匹配(假设节内没有其他字段/行包含[
)
结果将出现在捕获的组中
仅供参考,您可以使用较新的
regex
模块和命名的捕获组:
import regex as re
rx = re.compile("""
(?(DEFINE)
(?<section>^\[Section\ \d+\])
)
(?§ion)
(?:(?!(?§ion))[\s\S])*
^\s*name\s*=\s*\K(?P<name>.+)$
""", re.VERBOSE|re.MULTILINE)
string = """
[Section 1]
title = RegEx
name = Joe
color = blue
[Section 2]
height = 101
name = Gray
"""
names = [match.group('name') for match in rx.finditer(string)]
print(names)
# ['Joe', 'Gray']
将regex作为re导入
rx=重新编译(“”)
(?(定义)
(?^\[节\\d+\])
)
(?§ion)
(?:(?!(?§ion))[\s\s])*
^\s*name\s*=\s*\K(?P.+)$
“”,re.VERBOSE | re.MULTILINE)
string=”“”
[第1条]
title=RegEx
姓名=乔
颜色=蓝色
[第2条]
高度=101
名称=灰色
"""
names=[match.group('name'),用于rx.FindItemer(字符串)中的匹配项]
打印(姓名)
#[‘乔’、‘格雷’]
请参阅。让您开始:我已经尝试了ConfigParser,唯一不喜欢更改配置文件格式的是它。我不想删除选项卡并在每个小节上重新插入它们。谢谢,我会尝试一下