简体   繁体   中英

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM