Click here to Skip to main content
15,887,477 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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*)
is what I'm using.
Posted

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 $
are matching beginning end of string.

[Edit]
Regarding your comment I tested on RegExr. With omitting ^ and $ it worked fine. But I also found a shorter one
(\*\.[a-zA-Z0-9]+\s*\,?\s*)+

Almost the same that you came up with but this one also matches whitespace in front and behind comma.
[/Edit]
 
Share this answer
 
v3
Comments
agent154 11-Jan-12 20:51pm    
This seems to work, but only for two substrings. If I go beyond and add a third, then it matches only the third. I'm using http://gskinner.com/RegExr/ to test this.
Michel [mjbohn] 12-Jan-12 8:37am    
I updated my solution
agent154 12-Jan-12 9:45am    
You did in fact need the ^ and $. I think that might have been all I was missing. After adding those back into your modified solution, it seems to do what I want. Without it, it will still evaluate as 'true' if my first parameter is valid and the rest are not.

^(\*\.[a-zA-Z0-9]+\s*\,?\s*)+$ is what seems to work.
Hi,
use ?(question mark) after *,*? it denote * may present or absent..try it
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900