简体   繁体   English

将字符串中的值提取到数组中

[英]Extract values from a string into arrays

I have a string like this:我有一个这样的字符串:

john "is my best buddy" and he loves "strawberry juice"约翰“是我最好的伙伴”,他喜欢“草莓汁”

I want to-我想要-

  • Extract texts within double-quotes into a string array array1将双引号内的文本提取到字符串数组array1
  • Split texts outside of double-quotes by spaces and then insert them into another string array ( array2 ).用空格分割双引号之外的文本,然后将它们插入另一个字符串数组 ( array2 )。

Output:输出:

array1[0] : is my best buddy array1[0] : 是我最好的伙伴

array1[1] : strawberry juice array1[1] : 草莓汁

array2[0] : john array2[0] :约翰

array2[1] : and array2[1] :和

array2[2] : he array2[2] :他

array2[3] : loves array2[3] : 喜欢

Any help is appreciated.任何帮助表示赞赏。

Clearly, this is a call for Regular Expressions:显然,这是对正则表达式的调用:

var str = @"john ""is my best buddy"" and he loves ""strawberry juice""";

var regex = new Regex("(\"(?'quoted'[^\"]+)\")|(?'word'\\w+)",
                   RegexOptions.Singleline|RegexOptions.Compiled);

var matches = regex.Matches(str);

var quotes = matches.Cast<Match>()
                    .SelectMany(m => m.Groups.Cast<Group>())
                    .Where(g => g.Name == "quoted" && g.Success)
                    .Select(g => g.Value)
                    .ToArray();

var words = matches.Cast<Match>()
                    .SelectMany(m => m.Groups.Cast<Group>())
                    .Where(g => g.Name == "word" && g.Success)
                    .Select(g => g.Value)
                    .ToArray();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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