正则表达式匹配数字或UUID

时间:2013-12-12 19:59:30

标签: regex uuid

我需要与UUID和数字松散匹配的正则表达式。我希望我的文件名格式为:

results_SOMETHING.csv

理想情况下,这应该是数字(运行脚本的次数)或UUID。

这个正则表达式包含大量文件名:

 ^results_?.*.csv$

和这一个:

 ^results_?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}.csv$

仅匹配UUID。我想要一个正则表达式介于两者之间的正则表达式。大多数情况下,我不希望像result__123.csv这样的匹配。

2 个答案:

答案 0 :(得分:10)

注意:这不会直接回答OP问题,但鉴于标题,它会出现在搜索中。

这是一个正确的正则表达式,用于匹配基于this format 的uuid而不包含十六进制字符约束:

(\w{8}(-\w{4}){3}-\w{12}?)

如果您希望它只匹配十六进制字符,请使用:

/([a-f\d]{8}(-[a-f\d]{4}){3}-[a-f\d]{12}?)/i

(注意Javascript中使用的/分隔符和/i标志表示不区分大小写;根据您的语言,您可能需要以不同的方式编写,但您肯定希望同时处理和大写字母)。

如果您在results_前加.csv并附加^results_([a-z\d]{8}(-[a-z\d]{4}){3}-[a-z\d]{12}?).csv$,则会出现以下情况:

{{1}}

答案 1 :(得分:1)

-----已编辑/更新-----

根据你留下的评论,还有一些你想要匹配的其他模式(这个问题我不清楚)。这使得它更具挑战性 - 总结我目前的理解:

results.csv                                         - match (NEW)
results_1A.csv                                      - match (NEW)
results_ABC.csv                                     - ? no match (I assume)
result__123.csv                                     - no match
results_123.csv                                     - match
Results_123.cvs                                     - ? no match
results_0a0b0c0d-884f-0099-aa95-1234567890ab.csv    - match

根据上述“规范”,您会发现以下修改工作:

results(?:_(?:[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}|(?=.*[0-9])[A-Z0-9]+))?\.csv

打破它:

results               matches characters "results" literally
(?:_ ….)?             non-capturing group, repeated zero or one time:
                      "this is either there, or there is nothing"
[0-9a-f]{8}-          exactly 8 characters from the group [0-9a-f]
                      followed by hyphen "-"
(?:[0-9a-f]{4}-){3}   ditto but group of 4, and repeated three times
[0-9a-f]{12}          ditto, but group of 12
|                     OR...
(?=.*[0-9]+)          at least one number following this
[A-Z0-9]+             at least one capital letter or number
\.csv                 the literal string ".csv" (the '.' has to be escaped)

demonstration on regex101.com

相关问题