Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex C# problem

Tags:

c#

regex

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!

like image 758
Seattle Leonard Avatar asked Oct 27 '10 17:10

Seattle Leonard


2 Answers

"[^"]+"(?=;)|[^;]+(?=;)

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.

"([^"]+)";|([^;]+);
like image 115
Doug Domeny Avatar answered Oct 13 '22 14:10

Doug Domeny


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)

like image 35
OmnipotentEntity Avatar answered Oct 13 '22 15:10

OmnipotentEntity