【发布时间】:2010-10-04 01:38:59
【问题描述】:
如何修复此 RegEx 以选择性地捕获文件扩展名?
我正在尝试将字符串与可选组件匹配,但似乎有问题。 (匹配的字符串来自打印机日志。)
我的正则表达式(.NET Flavor)如下:
.*(header_\d{10,11}_).*(_.*_\d{8}).*(\.\w{3,4}).*
-------------------------------------------
.* # Ignore some garbage in the front
(header_ # Match the start of the file name,
\d{10,11}_) # including the ID (10 - 11 digits)
.* # Ignore the type code in the middle
(_.*_\d{8}) # Match some random characters, then an 8-digit date
.* # Ignore anything between this and the file extension
(\.\w{3,4}) # Match the file extension, 3 or 4 characters long
.* # Ignore the rest of the string
我希望它匹配如下字符串:
str1 = "header_0000000602_t_mc2e1nrobr1a3s55niyrrqvy_20081212[1].doc [Compatibility Mode]"
str2 = "Microsoft PowerPoint - header_00000000076_d_al41zguyvgqfj2454jki5l55_20071203[1].txt"
str3 = "header_00000000076_d_al41zguyvgqfj2454jki5l55_20071203[1]"
捕获组返回如下内容:
$1 = header_0000000602_
$2 = _mc2e1nrobr1a3s55niyrrqvy_20081212
$3 = .doc
如果没有找到文件扩展名,$3 可以为空。 $3 是可选部分,您可以在上面的 str3 中看到。
如果我添加“?”到第三个捕获组“(.\w{3,4})?”的末尾,RegEx 不再为任何字符串捕获 $3。如果我添加“+”而不是“(.\w{3,4})+”,RegEx 将不再捕获 str3,这是意料之中的。
我觉得使用“?”在第三个捕获组的末尾是合适的事情,但它不像我预期的那样工作。我可能对我用来忽略部分字符串的“.*”部分太天真了。
没有按预期工作:
.*(header_\d*_).*(_.*_.{8}).*(\.\w{3,4})?.*
【问题讨论】:
-
您使用的是哪个正则表达式实现?