如何从文本解析参数?

时间:2019-04-02 11:50:54

标签: python regex

我的文字如下:

ENGINE = CollapsingMergeTree (
    first_param
    ,(
        second_a
        ,second_b, second_c,
        ,second d), third, fourth)

引擎可以不同(而不是CollapsingMergeTree,可以有不同的单词,ReplacecingMergeTree,SummingMergeTree ...),但是文本始终为ENGINE = word()格式。 “ =”符号周围可以有空格,但这不是强制性的。 括号内有几个参数,通常是单个单词和逗号,但某些参数在括号内,如上例中的第二个。 换行符可以在任何地方。行可以以逗号,括号或其他任何内容结尾。

我需要提取n个参数(我不知道提前多少个)。在上面的示例中,有4个参数:

  1. first = first_param

  2. second =(second_a,second_b,second_c,second_d)[带括号的摘录]

  3. 第三=第三

  4. 第四=第四

如何使用python(正则表达式或其他任何东西)来做到这一点?

2 个答案:

答案 0 :(得分:0)

您可能想针对任何语言使用适当的解析器(并查看如何手动为简单语言解析器),但是由于此处所显示的内容看起来与Python兼容,因此您可以使用ast模块(来自标准库)将其解析为Python,然后处理结果。

答案 1 :(得分:0)

我为您的问题想出了一个正则表达式解决方案。我尽力使正则表达式模式保持“通用”,因为我不知道您的文本中是否总会有换行符和空格,这意味着该模式会选择很多空格,然后将其删除。 / p>

#Import the module for regular expressions
import re

#Text to search. I CORRECTED IT A BIT AS YOUR EXAMPLE SAID second d AND second_c WAS FOLLOWED BY TWO COMMAS. I am assuming those were typos.
text = '''ENGINE = CollapsingMergeTree (
    first_param
    ,(
        second_a
        ,second_b, second_c
        ,second_d), third, fourth)'''

#Regex search pattern. re.S means . which represents ANY character, includes \n (newlines)
pattern = re.compile('ENGINE = CollapsingMergeTree \((.*?),\((.*?)\),(.*?), (.*?)\)', re.S) #ENGINE = CollapsingMergeTree \((.*?),\((.*?)\), (.*?), (.*?)\)

#Apply the pattern to the text and save the results in variable 'result'. result[0] would return whole text.
#The items you want are sub-expressions which are enclosed in parentheses () and can be accessed by using result[1] and above
result = re.match(pattern, text)

#result[1] will get everything after theparenteses after CollapsingMergeTree until it reaches a , (comma), but with whitespace and newlines. re.sub is used to replace all whitespace, including newlines, with nothing
first = re.sub('\s', '', result[1])

#result[2] will get second a-d, but with whitespace and newlines. re.sub is used to replace all whitespace, including newlines, with nothing
second = re.sub('\s', '', result[2])

third = re.sub('\s', '', result[3])

fourth = re.sub('\s', '', result[4])

print(first)
print(second)
print(third)
print(fourth)

输出:

first_param
second_a,second_b,second_c,second_d
third
fourth

正则表达式说明: \ =转义控制字符,正则表达式将其解释为特殊字符。更多here

\(=转义括号

()=将括号中的表达式标记为子组。参见result [1]等等。

。 =匹配任何字符(包括换行符,因为re.S)

* =匹配0个或多个出现的前一个表达式。

? =匹配0或1次出现的前一个表达式。

注意:*?组合称为非贪婪重复,表示前面的表达式只匹配一次,而不是一遍又一遍。

我不是专家,但我希望我的解释正确。

我希望这会有所帮助。