【问题标题】:Using variables in re.sub [duplicate]在 re.sub 中使用变量 [重复]
【发布时间】:2020-06-08 14:25:57
【问题描述】:

我有一个包含不同环境部分的文件,如下所示:

#developmentsectionstart
  # development environment only
  context 'environment => development' do
    let(:trusted_facts) do
      super().merge('pp_apptier' => 'development')
    end
#developmentsectionend

#trainingsectionstart
  # training environment only
  context 'environment => training' do
    let(:trusted_facts) do
      super().merge('pp_apptier' => 'training')
    end
#trainingsectionend

我需要能够根据我放入列表的用户输入的环境删除部分。 例如envlist是用户输入的列表,allenvlist是文件中的所有环境。

我需要删除用户未输入的所有部分,例如测试、压力和训练 即从#trainingsectionstart#trainingsectionend 等的所有内容。 我尝试将用户输入的环境作为变量传递给re.sub。 不工作。

envlist = ['development','qa','production']
allenvlist = ['development','test','qa','stress','training','production']

new_env_list =[]
for element in allenvlist:
    if element not in envlist:
    new_env_list.append(element)
for i in range(0,len(new_env_list)):
    sectionstart = '#'+new_env_list[i]+'start'
    sectionend = '#'+new_env_list[i]+'end'
    newdata = re.sub(r'sectionstart.*?sectionend','', filedata, flags=re.DOTALL)

【问题讨论】:

    标签: python regex regexp-replace


    【解决方案1】:

    变量不会在字符串中展开。

    newdata = re.sub(sectionstart + '.*?' + sectionend,'', filedata, flags=re.DOTALL)
    

    如果变量可能包含特殊的正则表达式字符并且您希望按字面意思对待它们,您应该使用re.escape() 来保护它们。

    newdata = re.sub(re.escape(sectionstart) + '.*?' + re.escape(sectionend),'', filedata, flags=re.DOTALL)
    

    【讨论】:

      猜你喜欢
      • 2019-10-29
      • 2013-08-23
      • 1970-01-01
      • 2020-09-22
      • 2020-08-22
      • 1970-01-01
      • 1970-01-01
      • 2019-05-18
      • 2018-11-23
      相关资源
      最近更新 更多