正则表达式以查找特定部分中的文本

时间:2016-09-01 15:24:57

标签: python regex

我有正则表达式问题。我的数据如下:

 $scope.$on('sample', function(event, month, element) { } 

我的问题是我是否可以编写正则表达式来仅从[第1节]中捕获'name'键?实质上,捕获可能存在于多个位置的密钥,但仅从特定部分捕获它。我将在python中实现它。 感谢

3 个答案:

答案 0 :(得分:0)

使用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']

答案 1 :(得分:0)

虽然我不会用正则表达式做这件事,因为你问:

\[Section 1\][^[]*name\s*=\s*(.*)

[^[]位可防止正则表达式过于贪婪并匹配指定节之外的“名称”(假设节中没有其他字段/行包含[)。

结果将在捕获的组中。

https://regex101.com/r/uC7xD1/1

答案 2 :(得分:0)

仅供参考,您可以使用较新的regex模块和命名捕获组:

import regex as re

rx = re.compile("""
            (?(DEFINE)
               (?<section>^\[Section\ \d+\])
            )
            (?&section)
            (?:(?!(?&section))[\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']

请参阅a demo on regex101.com