文件名的验证器,带有花括号之间的自定义单词

时间:2014-08-17 16:59:58

标签: c# regex

我有正则表达式:

[\w,\s-]+\.[A-Za-z]+$

和文件名:

test-file_name-5.pdf

它运作正常。但现在我想添加这样的东西:

my-filename{time}.pdf

或者这个:

test{word}hello.pdf

正则表达式应该接受它。

如果只有开/大花括号,它应该失败。大括号可以包含a-Z0-9

我尝试使用RegExr,但无法做到。

1 个答案:

答案 0 :(得分:2)

您可以使用以下正则表达式:

^[\w,\s-]+(?:(?:{[A-Za-z\d]+}[\w,\s-]*)?)*\.[A-Za-z]+$

<强>解释

^                   # Assert position at the beginning of the string
[\w,\s-]+           # Beginning of the filename
(?:                 # Begin group
  (?:               #   Begin group
    {[A-Za-z\d]+}   #     Match {...} part
    [\w,\s-]*       #     Followed by optional characters
  )?                #   Make the group optional
)*                  # Repeat the group zero or more times
\.[A-Za-z]+         # Match the filename extension
$                   # Assert position at the end of the string

匹配:

test-file_name-5.pdf
my-filename{23m}.pdf
test{word1}hello{word2}xyz.pdf
test{word}hello.pdf

但不匹配:

foo-filename{23m.pdf
foo-filename23m}.pdf

RegEx Demo