寻找文本

时间:2016-06-14 23:49:39

标签: python regex python-3.x

我正在遍历许多.PHP文件,将它们视为纯文本,我试图找到某些函数的文本参数。

PHP文件中的函数都是使用\L10n::调用的,然后使用字符串参数。

我想要找到的文字示例如下。

我最幸运的是使用以下正则表达式来正确地找到它。

pattern = re.compile("L10n::[\w]+\((?:\'(.*?)\')\,?\s?(?:\'(.*?)\')*", re.MULTILINE | re.IGNORECASE | re.DOTALL)

OR

pattern = re.compile("\\L10n::(.*?)\('(.*?)'\)", re.MULTILINE | re.IGNORECASE | re.DOTALL)


bar\L10n::__('Double _')baz
bar\L10n::esc_attr__('Escape Attributes __')baz
bar\L10n::esc_html__('Escapted HTML __')baz
bar\L10n::_e('Echos')baz
bar\L10n::esc_html_e('Echo Escaped HTML')baz
bar\L10n::_x('Underscore X')baz
bar\L10n::_ex('Echo underscore x')baz
bar\L10n::esc_attr_x('Escape Attribute X')baz
bar\L10n::esc_html_x('Escaped HTML X')baz
bar\L10n::_n('Nothing')baz
bar\L10n::_nx('No X')baz
bar\L10n::_n_noop('N No-Op')baz
bar\L10n::_nx_noop('No X No-Op')baz

话虽如此,有些人会采取多种论点

bar\L10n::_n('Text 1', 'Text 2', $variable)

在这些情况下,我想要Text 1和Text 2,但不是$ variable。

为了让它变得更有趣......有时参数不是全部都在一行。

bar\L10n::_n(
    'Text 1',
    'Text 2',
    $variable
)

我上面的第一个正则表达式模式失败,如果文本里面有一个转义,例如'看看那些不在这里的人'

如果有多个文本变量,我上面的第二个正则表达式模式就会失败。 (它也会调出_n部分,但没关系)

任何帮助都将不胜感激。

编辑:

我还应该声明,文件中还有其他功能,我希望忽略它。

例如:

foo\file::__('function to ignore')

我不想与这些匹配。

我还希望匹配L10n函数在其他函数中用作参数的位置。

EG

bar\file::__(bar\L10n::_e('Text 1'), 'Other variable to ignore')

1 个答案:

答案 0 :(得分:0)

让我试试这个:

import re
input = """bar\L10n::__('Double _')baz
bar\L10n::esc_attr__('Escape Attributes __')baz
bar\L10n::_n(
    'Text 1',
    'Text 2',
    $variable
)"""
input = input.replace('\n', '')
reg = re.compile('\'(.*?)\'')
foo = reg.findall(input)

给出一个数组:

['Double _', 'Escape Attributes __', 'Text 1', 'Text 2']

现在,如果您希望获得一个好玩并将所有内容编入索引,以便您可以轻松迭代所有内容,该怎么办?

import re
input = """bar\L10n::__('Double _', 'another')baz
bar\L10n::esc_attr__('Escape Attributes __')baz
bar\L10n::_n(
    'Text 1',
    'Text 2',
    $variable
)"""
dict = {}
input = input.split('bar\\L10n::')
regName = re.compile('(.*)\(')
regAttr = re.compile('\'(.*?)\'')
for i in input:
    foo = regName.search(i)
    if foo is not None:
        dict[foo.group(1)] = regAttr.findall(i)

会生成一个类似的字典:

{'__': ['Double _', 'another'], '_n': ['Text 1', 'Text 2'], 'esc_attr__': ['Escape Attributes __']}

希望这有帮助!

我有一个名为Rubular的网站用于正则表达式,它应该用于Ruby,但我将它用于Ruby,Python和Perl正则表达式。如果您认为自己会做更多的正则表达式,我建议您查看一下。

编辑:(在评论中讨论后)

import re

globalDict = {}

for file in directory: # pseudo-code, implement this loop yourself

    fileContents = """bar\L10n::__('Double _', 'another')baz
    bar\L10n::esc_attr__('Escape Attributes __')baz
    bar\L10n::_n(
        'Text 1',
        'Text 2',
        $variable
    )"""
    regAttr = re.compile('\'(.*?)\'')
    for i in regAttr.findall(fileContents):
        if i in globalDict.keys():
            globalDict[i].append('filename')
        else:
            globalDict[i] = ['filename']