在 python 中实施正则表达式时,续行后出现意外字符

Unexpected Character after line continuation while implementing regex in python

我正在尝试使用正则表达式在文件夹中搜索文件,但是当我尝试在变量中传递正则表达式时

file_to_search = re.search('Weekly' +(\d{2})[/.-](\d{2})[/.-](\d{4})$ + 'Scores.xlsx')

我要搜索的文件模式是

每周 02.28.2018 Scores.xlsx

每周 03.05.2018 Scores.xlsx

到目前为止,我不关心文件是否是:

每周 99.99.9999 Scores.xlsx

但我在行尾收到以下错误。

SyntaxError: unexpected character after line continuation character.

file_to_search = re.search('Weekly' +\d{2}\d{2}\d{4}+ 'Scores.xlsx')

                                                          ^
  • re.search 需要一个模式和一个文本。你遗漏了其中一个。

  • Python 没有正则表达式的字面语法,这意味着 Python 中的所有正则表达式都需要是字符串。

  • 你的意思可能不是.xlsx

  • 您需要转义扩展点。 (您不需要转义日期中的点,因为它在方括号内,一个字符 class。)

  • 您需要考虑 space。文字 space 在这里工作正常;如果可能的话,它可能是一个标签或其他东西 \s 会更可取。

  • 我使用原始字符串文字 r'...' 所以我可以写 \d 而不是 \d

现在一起:

match = re.search(r'^Weekly \d{2}[/.-]\d{2}[/.-]\d{4} Scores\.xslx$', file_to_test)

让你的生活更简单:

>>> import re
>>> matcher = re.compile( r'Weekly \d\d\.\d\d\.\d\d\d\d Scores.xlsx' )
>>> a = '''The file pattern I am trying to search is
... 
... Weekly 02.28.2018 Scores.xlsx
... 
... Weekly 03.05.2018 Scores.xlsx
... 
... As of now I dont care if the file is:
... 
... Weekly 99.99.9999 Scores.xlsx
... 
... But I get the below error pointing at the end of the line.'''
>>> matcher.findall( a )
['Weekly 02.28.2018 Scores.xlsx', 'Weekly 03.05.2018 Scores.xlsx', 'Weekly 99.99.9999 Scores.xlsx']
>>>

我希望这能回答你的问题 =)

如果您想使用文件:

>>> filenames = matcher.findall( a )
>>> filenames.append( 'somefile.txt' )
>>> for f in filenames : print f, matcher.match( f ) is not None
... 
Weekly 02.28.2018 Scores.xlsx True
Weekly 03.05.2018 Scores.xlsx True
Weekly 99.99.9999 Scores.xlsx True
somefile.txt False
>>>