[英]REGEX Expression C#. Split string by whitespace outside the quotation marks
I'm trying to define a regular expression for the Split function in order to obtain all substring split by a whitespace omitting those whitespaces that are into single quotation marks. 我正在尝试为Split函数定义一个正则表达式,以便通过省略所有用单引号引起来的空格来获得所有子字符串分割。
Example: 例:
key1:value1 key2:'value2 value3' key1:value1 key2:'value2 value3'
i Need these separated values: 我需要这些分开的值:
key1:value1 KEY1:数值
key2:'value2 value3' key2:“ value2 value3”
I'm tried to perform this in different ways: 我试图以不同的方式执行此操作:
What i am wrong with this code? 我对此代码有何疑问?
Could you please help me with this? 你能帮我这个忙吗?
Thanks in advance 提前致谢
A working example: 一个工作示例:
(\\w+):(?:(\\w+)|'([^']+)')
(\w+) # key: 1 or more word chars (captured)
: # literal
(?: # non-captured grouped alternatives
(\w+) # value: 1 or more word chars (captured)
| # or
'([^']+)' # 1 or more not "'" enclosed by "'" (captured)
) # end of group
Your try: 您的尝试:
(\\s)^('\\s')
(\\ S)^( '\\ S')
^
means beginning of line, \\s
is a white-space characters. ^
表示行的开头, \\s
是空格字符。 If you want to use the not-operator, this only works in a character class [^\\s]
-> 1 character not a white-space. 如果要使用非运算符,则仅适用于字符类
[^\\s]
-> 1个字符,而不是空格。
Try following : 尝试以下操作:
static void Main(string[] args)
{
string input = "key1:value1 key2:'value2 value3'";
string pattern = @"\s*(?'key'[^:]+):((?'value'[^'][^\s]+)|'(?'value'[^']+))";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine("Key : '{0}', Value : '{1}'", match.Groups["key"].Value, match.Groups["value"].Value);
}
Console.ReadLine();
}
var st = "key1:value1 key2:'value2 value3'";
var result = Regex.Matches(st, @"\w+:\w+|\w+:\'[^']+\'");
foreach (var item in result)
Console.WriteLine(item);
The result should be: 结果应为:
key1:value1
key2:'value2 value3'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.