I have a regular expression with the following pattern in C#
Regex param = new Regex(@"^-|^/|=|:");
Basically, its for command line parsing.
If I pass the below cmd line args it spilts C: as well.
/Data:SomeData /File:"C:\Somelocation"
How do I make it to not apply to characters inside double or single quotes ?
You can do this in two steps:
Use the first regex
to split the string into the different arguments. Then use the regex
to split each of the arguments into parameter/value pairs.
Explanation:
Basically, it looks ahead in the string if there is an even number of quotes ahead. If there is, we’re outside of a string. However, this (somewhat manageable) regex only handles double quotes, and only if there are no escaped quotes inside those.
The following regex handles single and double quotes, including escaped quotes, correctly. But I guess you’ll agree that if anybody ever finds this in production code, I’m guaranteed a feature article on The Daily WTF:
Further explanation of this monster here.