正则表达式不匹配字符串末尾的任何内容

regex match nothing at the end of string

我正在尝试匹配文件名中由点分隔的任意数量的文字 # 符号。文字 # 符号必须在两边用点分隔,除非它是文件名的最后一个元素。我可以创建一个模式来执行第一个(匹配任何由点包围的文字 # 符号)但我不能同时允许第二个(以文字 # 符号结尾且没有尾随点的文件名)。

例如,以下将匹配:

bob.#
bob.#.
bob.#.exr
bob.##.mary.tif
bob.####.png

而以下将不匹配:

bob.#string.exr
bob.string#.exr

我目前的模式(在 python 中表示为原始字符串)是:

(.*)(\.#+)((?:\.+.*|$))

很遗憾,它与我列表中的第一项不匹配:bob。#

我原以为最后一个非捕获组基本上会读作:

匹配文字点后跟 0 个或更多字符

匹配字符串的结尾

但在 regexr.com 中测试显示它不匹配 bob。#

提前感谢您提供任何线索!

你的表达似乎工作得很好,我仍然会把它修改成一些可能类似于的表达:

import re

regex = r"^([^.]*)(\.#+)(\..*)?$"

test_str ="""
bob.#
bob.#.
bob.#.exr
bob.##.mary.tif
bob.####.png
Whereas the following would not match:

bob.#string.exr
bob.string#.exr

"""

print(re.findall(regex, test_str,re.M))

输出

[('\nbob', '.#', ''), ('bob', '.#', '.'), ('bob', '.#', '.exr'), ('bob', '.##', '.mary.tif'), ('bob', '.####', '.png')]

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


正则表达式电路

jex.im 可视化正则表达式:

如果您希望它与整个元序列相匹配,这里有一个:

import re

pattern = re.compile(r'(\w+\.\#+(?:\.|$)\w*\.*\w*)')
test = ['bob.#', 'bob.#.', 'bob.#.exr', 'bob.##.mary.tif', 'bob.####.png', 'bob.#string.exr', 'bob.string#.exr']
for t in test:
    print(re.findall(pattern, t))

输出:

['bob.#']
['bob.#.']
['bob.#.exr']
['bob.##.mary.tif']
['bob.####.png']
[]
[]

^\w*?\.(#+)(\.\w*?)*?$

这个正则表达式匹配一个点前面的任意数量的单词字符(包括none),匹配一个或多个octothorpe符号,然后可选地匹配一个点和更多words/chars。

^\w*?\.(#+)(\.\w*?)*?$

^                         anchor to the start of the line
 \w*?                     get as many word characters as you want, but as few as you need
     \.                   match . literally
       (#+)               match one or more # literally. grouped for your convenience if you want to count how many times they appear or something.
           (      )*?     match zero or more of this group:
            \.            a literal dot...
              \w*?        ...and zero or more word characters, as few as needed.
                     $    ensure the string ends with this group.

Try it here!

关于这个正则表达式的一些注意事项:

  • 如果该行没有其他字符串,它只会匹配您的字符串。
  • octothorpes 已分组,稍后可以提取以进行计数(或任何您想要的)。
  • \w* 通常比 .* 更安全也更快——它专门查找单词字符 a-z, A-Z, 0-9, _ 而不是任何符号。作为一般规则,如果你可以让你的正则表达式更具体,你应该,以免你冒 catastrophic backtracking!
  • 的恐怖风险