需要正则表达式帮助 [英] Regular Expression help needed
问题描述
我正在尝试找出仅匹配格式正确的字符串的正则表达式,如果其中任何一部分无效,则返回false.
我的字符串采用文件系统通配符的格式,以逗号分隔,以允许将多个通配符放入一个字符串中.我能够提出一个正则表达式来匹配通配符,这没有问题,但是如果出现任何问题,我将无法使整个字符串无效.
例如,如果给出了"* .exe,.bat",则该名称应无效,因为.bat之前没有*.但是我的正则表达式仍然正确,因为它在其中找到* .exe
I''m trying to figure out a regex that will match only a properly formatted string, and return false if any part of it is invalid.
My string is in the format of filesystem wildcards separated by a comma to allow for multiple wildcards to be put in one string. I am able to come up with a regex to match a wildcard with no problem, but I cannot get one to invalidate the whole string if anything is amiss.
For example, if "*.exe, .bat" is given, then it should be invalid because there is no * before the .bat. However my regex still turns up true because it finds the *.exe in there
(\*\.[a-zA-Z0-9]+\,?\s*)
是我正在使用的.
推荐答案
有两种情况需要处理.
1)仅一种搜索模式
2)多个搜索模式
There are two cases to take care of.
1) Only one search pattern
2) More than one search pattern
((^\*\.[a-zA-Z0-9]+\,\s*)*(\*\.[a-zA-Z0-9]+\s*)
)
第一部分
The first part
(^\*\.[a-zA-Z0-9]+\,\s*)*
匹配零个或多个模式,后跟逗号,第二部分
matches for zero or more patterns followed by comma and the second part
(\*\.[a-zA-Z0-9]+\s*)
仅匹配一个或最后一个模式.
for only one or the last pattern.
^ and
匹配字符串的开头.
关于您的评论,我在RegExr上进行了测试.省略^和
are matching beginning end of string.
Regarding your comment I tested on RegExr. With omitting ^ and
这篇关于需要正则表达式帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!