Regex C# problem
I'm sure there is a simple solution, but I just seem to be missing it.
I need a regex to do the following:
asdf.txt;qwer
should match asdf.txt
"as;df.txt"开发者_开发知识库;qwer
should match as;df.txt
As you can see, I need to match up to the semi-colon, but if quotes exist(when there is a semi-colon in the value), I need to match inside the quotes. Since I am looking for a file name, there will never be a quote in the value.
My flavor of regex is C#.
Thanks for your help!
"[^"]+"(?=;)|[^;]+(?=;)
This matches text within double quotes followed by a semicolon OR text followed by a semicolon. The semicolon is NOT included in the match.
EDIT: realized my first attempt will match the quotes. The following expression will exclude the quotes, but uses subexpressions.
"([^"]+)";|([^;]+);
This should do you:
(".*"|.*);
It technically matches the semicolon as well, but you can either chop that off or just use the backreference (if C# supports backreferences)
This will match up to a ;
if there are no quotes or the quoted text followed by a ;
if there are quotes.
("[^"]+";|[^;]+;)
Do you need to use regex, you could just use the C# string method contains:
string s = "asdf.txt;qwer";
string s1 = "\"as;df.txt\";qwer";
return s.Contains("asdf.txt"); //returns true
return s1.Contains("\"as;df.txt\""); //returns true
If you are looking for the two explicit strings asdf.txt and as;df.txt these can then simply be your two regex epressions. So something like the following.
Matches matches = Regex.Matches('asdf.txt;qwer',"asdf.txt");
and
Matches matches = Regex.Matches('"as;df.txt";qwer',"as;df.txt");
Enjoy!
精彩评论