pattern.match无法识别带有特殊字符“ ^”的文件名(RegEx函数)

时间:2018-11-25 09:58:22

标签: python regex utf-8

我正在Winows 10上使用Python 3.6.5。

我无法验证目录中是否存在文件。 问题似乎来自特殊字符“ ^”。

当我运行下面的代码时,os.listdir()函数会很好地列出“ WITHOUT_CIRCUMFLEX”和“ ^ WITH_CIRCUMFLEX”文件。 但是,模式“ pattern.match(文件)...”无法识别文件“ ^ WITH_CIRCUMFLEX”!

有人会解决这个问题吗? 谢谢您的帮助

# coding: utf-8

import pandas as pd import os.path import regex path = "C:\Users\David\test" list_name = ['WITHOUT_CIRCUMFLEX', '^WITH_CIRCUMFLEX']

df_empty = pd.DataFrame()

for name in list_name: df_empty.to_pickle('{path}\{name}.pkl'.format(**locals())) pattern = regex.compile('{name}.pkl'.format(**locals()))

$username = "domain\administrator" $password = "Your password" $credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username, $password $computers = @("nr1", "nr2", "nr3") foreach($computer in $computers){ $hotspot = Invoke-Command -ComputerName $computer -credential $credential -scriptblock { $hotspot = Get-Service "icssvc" if($hotspot.Status -eq "Running"){ Write-Host "Hotspot is turned on on $computer" -ForegroundColor Red try{ Stop-Service "icssvc" Write-Host "Successfully stopped service on $computer" -ForegroundColor Green }catch{ Write-Host "Unable to stop service on $computer" -ForegroundColor Red } }else{ Write-Host "No Hotspot running on $computer" -ForegroundColor Green } }

2 个答案:

答案 0 :(得分:4)

^是一个正则表达式元字符,因此它与文本中的文字^字符不匹配。您需要转义这样的字符:

'\^WITH_CIRCUMFLEX'

如果您的输入是从其他来源生成或获取的,请使用regex.escape()函数为您转义元字符:

for name in list_name:
    df_empty.to_pickle('{path}\{name}.pkl'.format(**locals()))
    name = regex.escape(name, special_only=True)
    pattern = regex.compile('{name}.pkl'.format(**locals()))

但是,如果您要匹配文件,则当前没有使用正则表达式的任何原因。您的模式最多将匹配以{name}.pkl结尾的任何文件名。您最好使用glob module

import glob

for name in list_name:
    ...
    escaped_name = glob.escape(name)
    files = glob.glob('*{}.pkl'.format(escaped_name))

答案 1 :(得分:1)

^是一个正则表达式元字符,因此您必须对其进行转义。最简单的方法是使用regex.escape函数,该函数自动将任意字符中的元字符转义。

所以不是

pattern = regex.compile('{name}.pkl'.format(**locals()))

使用

pattern = regex.compile(regex.escape('{name}.pkl').format(**locals()))
相关问题