[英]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
asdf.txt;qwer
应匹配asdf.txt
"as;df.txt";qwer
should match as;df.txt
"as;df.txt";qwer
应匹配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#. 我的正则表达式是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) 它在技术上也与分号匹配,但您可以将其关闭或仅使用反向引用(如果C#支持反向引用)
This will match up to a ;
这将匹配到;
if there are no quotes or the quoted text followed by a ;
如果没有引号或引用的文字后跟a ;
if there are quotes. 如果有报价。
("[^"]+";|[^;]+;)
Do you need to use regex, you could just use the C# string method contains: 你需要使用正则表达式,你可以只使用C#字符串方法包含:
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. 如果您正在寻找两个显式字符串asdf.txt和; df.txt,那么这些只能是您的两个正则表达式。 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! 请享用!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.