正则表达式可选择匹配文件名末尾的 3 位数字

我一生都无法弄清楚如何让这些匹配:


File name without 3 digit end.jpg

File name with 3 digit 123.gif

Single 123.jpg

Single.png

但不是这些:


Single 1.jpg

Single 123b.gif

More words 123b.png

到目前为止,我能做到的最好的就是这个表达式:


^[^\s]((?!\s{2})(?!,\S).)*\b(\p{L}+|\d{3})\.\w{3}$

但它无法匹配Single.png,仍然匹配Single 123b.gifand More words 123b.png。我想我明白为什么它不起作用,但我不知道如何让它正确,我一直在努力和谷歌搜索 2 天。


我的完整规则是:在文件扩展名之前可以选择正好 3 个数字,3 个字母的文件扩展名,文件名中没有双空格,逗号之后但不是逗号之前有一个空格。


慕无忌1623718
浏览 269回答 3
3回答

长风秋雁

您可以使用包含 3 个数字或一系列非数字的交替组,前面有一个单词边界断言:^.*?\b(?:\d{3}|\D+)\.\w{3}$演示:https ://regex101.com/r/A9iSVE/3

德玛西亚99

为了将您的要求考虑到逗号和双空格,一种选择可能是使用 2 个负前瞻来断言字符串不包含双空格并且在逗号之前不包含空格。\s如果要匹配空白字符而不是单个空格,则可以使用。^(?!.*[ ]{2})(?!.* ,).*\b(?:\p{L}+|\d{3})\.\w{3}$那将匹配^字符串的开始(?!.*[ ]{2})断言不是 2 个空格(?!.* ,)断言不是一个空格和一个逗号.*\b匹配任何字符 0+ 次,后跟单词边界(?:\p{L}+|\d{3})匹配 1+ 次字母或 3 位数字\.\w{3}匹配.和 3 个单词字符$字符串结束正则表达式演示| C# 演示

慕雪6442864

您可以在不回溯的情况下满足指定的规则(当前接受的答案就是这样)。指定的规则是(为了清楚起见重新措辞):文件名必须满足以下条件:它不得包含多个空格字符的序列。逗号后面必须有一个空格字符。文件名词干可以有一个 3 位数的后缀。文件扩展名必须由 3 个字母组成。为此:^(?<prefix>[^,&nbsp;]+(,?&nbsp;[^,&nbsp;]+)*)(?<suffix>\d\d\d)?(?<extension>.\p{L}\p{L}\p{L})$会成功的,没有花哨的前瞻,没有回溯。分解成碎片,你会得到:^&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # * match start-of-text, followed by(?<prefix>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# * a named group, consisting of&nbsp; [^,\x20]+&nbsp; &nbsp; &nbsp; &nbsp; #&nbsp; &nbsp;* 1 or more characters other than comma or space, followed by&nbsp; (&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #&nbsp; &nbsp;* a group, consisting of&nbsp; &nbsp; ,?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp; &nbsp;* an optional comma, followed by&nbsp; &nbsp; \x20&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp; &nbsp;* a single space character, followed by&nbsp; &nbsp; [^,\x20]+&nbsp; &nbsp; &nbsp; #&nbsp; &nbsp; &nbsp;* 1 or more characters other than comma or space&nbsp; )*&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp; &nbsp;with the whole group repeated zero or more times)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #&nbsp; &nbsp;followed by(?<suffix>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;# * an optional named group (the suffix), consisting of&nbsp; \d\d\d&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp;* 3 decimal digits)?&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;#&nbsp; &nbsp;followed by(?<extension>&nbsp; &nbsp; &nbsp; # * a mandatory named group (the filename extension), consisting of&nbsp; .\p{L}\p{L}\p{L} #&nbsp; &nbsp;* 3 letters.)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; #&nbsp; &nbsp;followed by$&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; # end-of-text
打开App,查看更多内容
随时随地看视频慕课网APP