示例“[狗]猫[狮子]熊[狗] [小鼠]骆驼[狮子] [熊]斑马”
从上面的字符串中,我想要一个像下面这样的返回字符串。
- > 小鼠/狮子/熊/狗
规则是:
我在下面的C#中试过这个,但没有成功。
有人能给我最好的C#练习吗?
string input = "[dogs] cats [lions] bears [Dogs] [mice] camels [lions] [bears] zebras";
var pattern = @"(\[.+?\])";
Regex regex = new Regex(pattern);
input = regex.Matches(input)[0].ToString();
string[] words = input.Split(' ');
var lambda = words.Select(s => s).Distinct();
string re= string.Join(" / ", lambda.Select(item => item.ToString()));
// want re to be like --> "mice / lions / bears / dogs"
答案 0 :(得分:2)
试试这个:
var input = "[dogs] cats [lions] bears [Dogs] [mice] camels [lions] [bears] zebras";
var pattern = @"(\[.+?\])";
var regex = new Regex(pattern);
var rnd = new Random();
var result =
String.Join(
" / ",
regex
.Matches(input)
.OfType<Match>()
.Select(x => x.Value)
.Select(x => x.Substring(1, x.Length - 2).ToLower())
.Distinct()
.OrderBy(x => rnd.Next()));
我得到的结果如下:
lions / mice / bears / dogs dogs / mice / bears / lions
答案 1 :(得分:1)
这应该有效:
string input = "[dogs] cats [lions] bears [Dogs] [mice] camels [lions] [bears] zebras";
var pattern = @"\[(.+?)\]";
Regex regex = new Regex(pattern);
var random = new Random();
var matchedItems = regex.Matches(input).Cast<Match>()
.Select(m => m.Groups[1].Value.ToLower())
.Distinct().OrderBy(i => random.Next());
var re = string.Join(" / ", matchedItems);
变更:
在您的正则表达式中移动了分组(而不是将其全部括起来,我们只包括该值)
使用正则表达式引擎提供的组来获取值
选择每个匹配,而不仅仅是第一个