如何在 Python 中使用正则表达式搜索除以反斜杠的数据

How to search for data divided by backslash using regular expressions in Python

我正在尝试列出除以单个反斜杠的数据的一部分。该部分只是一个六位数字。我需要引用反斜杠的原因是我会将此代码用于更多文件,其中可能包括数据组中的其他六位(和更多)数字。

代码示例如下:

>>> layer = arcpy.mapping.Layer("J:\abcd\blabla.lyr")
>>> print layer.dataSource
C:\Users6938\AppData\Roaming\ESRI\Desktop10.0\ArcCatalog\...
>>> result = re.search (r'([a-z]{1}[0-9]{6})', text)
>>> result.group(0)
u'416938'

但我想像这样包含反斜杠(显然这段代码行不通):

re.search (r'(\[0-9] {6}\)', text)

非常感谢任何帮助。谢谢

您需要转义反斜杠:

re.search (r'(\[0-9] {6}\)', text)

这是您可以用来提取完整单词的 6 位数字的代码:

import re
p = re.compile(ur'\b[0-9]{6}\b')
test_str = ur"C:\Users\416938\AppData\Roaming\ESRI\Desktop10.0\ArcCatalog"
match = re.search(p, test_str)
if match:
    print(match.group(0))

IDEONE demo

请注意 \b - a word boundary - 匹配以下位置:

  • Before the first character in the string, if the first character is a word character.
  • After the last character in the string, if the last character is a word character.
  • Between two characters in the string, where one is a word character and the other is not a word character.

如果你想匹配\...\内的6位数字序列你可以使用

(?<=\)[0-9]{6}(?=\)

或者,如果您想要匹配未包含其他数字(例如字母之间)的 6 位序列,请使用此正则表达式:

(?<!\d)[0-9]{6}(?!\d)

它包含 2 个环视。 (?<!\d) 确保 6 位序列之前没有数字,(?!\d) 确保它之后没有数字。

如果 windows 路径将始终具有给定的结构 C:\Users\[0-9]{6}\... - 这里我们不用复杂的转义正则表达式语法:

>>> text = r"C:\Users6938\AppData\Roaming\ESRI\Desktop10.0\ArcCatalog"
>>> match = text.split("\")[2]  # split at \ and grad third element
'416938'
>>> if match.isdigit() and len(match) == 6:  # check for digit and length 6
...