【问题标题】:Regex expression with [ and * in pythonpython中带有[和*的正则表达式
【发布时间】:2019-01-19 21:43:34
【问题描述】:

我有一个像这样行的文件

variable = epms[something][something]

我需要通过搜索 epms 找到这些行。

目前,我正在尝试这个:

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

但是,这找不到任何匹配项。我做错了什么?

【问题讨论】:

  • [.] 匹配文字点字符。您需要删除.s 周围的[]
  • 试试\^*epms[.*?][.*?]
  • 如果您正在寻找确切的字符串,为什么要使用正则表达式?

标签: python regex


【解决方案1】:

你可以使用模式:

epms\[[^]]+\]\[[^]]+\]
  • epms 匹配文字子串。
  • \[ 匹配 [
  • [^]]+ 否定字符集。除了] 之外的任何内容。
  • \] 匹配 ]
  • \[ 匹配 [
  • [^]]+ 否定字符集。除了] 之外的任何内容。
  • \] 匹配]

在 Python 中:

import re

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

【讨论】:

  • 感谢您的完整解释!
【解决方案2】:

试试这个模式epms\[.*\]\[.*\]

例如:

import re

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

【讨论】:

    【解决方案3】:

    试试这个,在 Python3 中测试过:

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

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

    【讨论】:

      猜你喜欢
      • 2010-09-28
      • 1970-01-01
      • 2012-03-24
      • 2012-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多