【问题标题】:Regular expression in python: matching a number as a variablepython中的正则表达式:将数字匹配为变量
【发布时间】:2018-10-15 02:54:26
【问题描述】:

我想使用“re”库来匹配我需要的字符串。

例如,我有一个如下所示的 for 循环,我想根据循环号查找它们结束的文件:

for ind in range(10):
    file_name = re.match(r'^abc.*\.\d{ind}', s)

但我认为这不是正确的方法,因为 ind 是一个变量?

例如,结果我想找到这些文件:

> ind==1 -> abc1     ind==2 -> abc2       ind==3 -> abc3

如果您告诉我编写这部分代码的正确方法,我将不胜感激。

【问题讨论】:

  • 您是否尝试过使用串联?
  • @CertainPerformance 我该怎么做?
  • 你想找到类似\d{3}(重复次数)还是正好是abc.*3
  • 我想知道你的代码是不是f'^abc.*\.\d{ {ind} }'。顺便说一句,此语法适用于 3.6 之后的版本(包含)

标签: python regex python-3.x


【解决方案1】:

(已编辑)

在字符串中放置变量名不会自动替换您的值。你要做的是format一个字符串。

for ind in range(10):
    file_name = re.match(r'^abc.*\.{}'.format(ind), s)

如果这有点混乱,你也可以使用旧语法

re.match(r'^abc.*\.%d' % ind, s)

【讨论】:

    【解决方案2】:

    请尝试:

    r'^abc.*[' + str(ind) + r']'
    

    您使用的令牌不正确。 {x} 意味着将前面的模式重复 x 次。因此\d{ind} 基本上表明您的文件将以ind 位数而不是数字本身结尾。

    [ind] 是您所需要的。

    【讨论】:

      【解决方案3】:

      在 python36 或更高版本上尝试此代码

      for ind in range(10):
          print(f'^abc.*\.\d{ {ind} }')
      

      【讨论】:

        猜你喜欢
        • 2023-03-15
        • 2023-02-03
        • 2016-03-25
        • 2015-07-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-01
        • 2016-10-22
        相关资源
        最近更新 更多