python中带[和*的正则表达式

2024-09-27 00:14:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的文件

variable = epms[something][something]

我需要通过搜索epms找到这些行。你知道吗

目前,我正在尝试:

regex = re.compile('[.]*epms\[[.]*\]\[[.]*\][.]*')

但是,这没有找到任何匹配项。我做错什么了?你知道吗


Tags: 文件revariablesomethingregexcompileepms
3条回答

试试这个模式epms\[.*\]\[.*\]。你知道吗

例如:

import re

with open(filename1) as infile:
    for line in infile:
        if re.search(r"epms\[.*\]\[.*\]", line):
            print(line)

试试这个,用Python3测试:

>>> s = 'variable = epms[something][something]'
>>> re.match(r'.*epms\[.*\]\[.*\]', s)
<_sre.SRE_Match object; span=(0, 37), match='variable = epms[something][something]'>

您不需要方括号来标识“任何字符”。你知道吗

您可以使用模式:

epms\[[^]]+\]\[[^]]+\]
  • epms匹配文字子字符串。你知道吗
  • \[匹配[。你知道吗
  • [^]]+取反的字符集。除了]之外的任何东西。你知道吗
  • \]匹配]。你知道吗
  • \[匹配[。你知道吗
  • [^]]+取反的字符集。除了]之外的任何东西。你知道吗
  • \]匹配]。你知道吗

在Python中:

import re

mystring = "variable = epms[something][something]"
if re.search(r'epms\[[^]]+\]\[[^]]+\]',mystring):
    print (mystring)

相关问题 更多 >

    热门问题