簡體   English   中英

正則表達式可選地匹配文件名末尾的3位數

[英]Regex to optionally match 3 digits at the end of file name

我不能為我的生活弄清楚如何讓這些匹配:

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.gifMore words 123b.png 我想我明白為什么它不起作用,但我無法弄清楚如何正確,我一直在苦苦掙扎和谷歌搜索2天。

我的完整規則是:在文件擴展名之前的末尾可選擇正好3位數,3個字母文件擴展名,文件名中沒有雙重空格,以及逗號之前但不是之前的單個空格。

您可以使用包含3位數字或非數字序列的替換組,前面是單詞邊界斷言:

^.*?\b(?:\d{3}|\D+)\.\w{3}$

演示: https//regex101.com/r/A9iSVE/3

要將你的requiremenet考慮到逗號和雙空格,一個選項可能是使用2個負向前瞻來斷言字符串不包含雙空格並且在逗號之前不包含空格。

如果要匹配空白字符而不是單個空格,可以使用\\s

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

這將匹配

  • ^字符串的開頭
  • (?!.*[ ]{2})斷言不是2個空格
  • (?!.* ,)斷言不是單個空格和逗號
  • .*\\b匹配任何字符0+次,后跟字邊界
  • (?:\\p{L}+|\\d{3})要么匹配1個字母或3個數字
  • \\.\\w{3}匹配. 和3個字的字符
  • $字符串結束

正則表達式演示 | C#演示

您可以滿足指定的規則而無需回溯(當前接受的答案可以)。 指定的規則是(為了清楚起見而改寫):文件名必須滿足以下條件:

  • 它不能包含多個空格字符的序列。
  • 逗號必須跟在它后面只有一個空格字符。
  • 文件名詞干可以有一個3位數的后綴。
  • 文件擴展名必須由3個字母組成。

為此:

^(?<prefix>[^, ]+(,? [^, ]+)*)(?<suffix>\d\d\d)?(?<extension>.\p{L}\p{L}\p{L})$

會做的伎倆,沒有花哨的前瞻,沒有回溯。 分成幾塊,你得到:

^                  # * match start-of-text, followed by
(?<prefix>         # * a named group, consisting of
  [^,\x20]+        #   * 1 or more characters other than comma or space, followed by
  (                #   * a group, consisting of
    ,?             #     * an optional comma, followed by
    \x20           #     * a single space character, followed by
    [^,\x20]+      #     * 1 or more characters other than comma or space
  )*               #     with the whole group repeated zero or more times
)                  #   followed by
(?<suffix>         # * an optional named group (the suffix), consisting of
  \d\d\d           #   * 3 decimal digits
)?                 #   followed by
(?<extension>      # * a mandatory named group (the filename extension), consisting of
  .\p{L}\p{L}\p{L} #   * 3 letters.
)                  #   followed by
$                  # end-of-text

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM