gpt4 book ai didi

c# - 正则表达式拆分字符串并将括号 [ ] 中的内容放入数组

转载 作者:太空宇宙 更新时间:2023-11-03 10:55:59 26 4
gpt4 key购买 nike

我正在尝试使用正则表达式将字符串拆分为 2 个数组,结果如下。

String str1 = "First Second [insideFirst] Third Forth [insideSecond] Fifth";

如何将 str1 拆分为 2 个如下所示的数组:

ary1 = ['First Second','Third Forth','Fifth'];
ary2 = ['insideFirst','insideSecond'];

最佳答案

这是我的解决方案

string str = "First Second [insideFirst] Third Forth [insideSecond] Fifth";
MatchCollection matches = Regex.Matches(str,@"\[.*?\]");
string[] arr = matches.Cast<Match>()
.Select(m => m.Groups[0].Value.Trim(new char[]{'[',']'}))
.ToArray();
foreach (string s in arr)
{
Console.WriteLine(s);
}

string[] arr1 = Regex.Split(str,@"\[.*?\]")
.Select(x => x.Trim())
.ToArray();
foreach (string s in arr1)
{
Console.WriteLine(s);
}

输出

insideFirst
insideSecond
First Second
Third Forth
Fifth

关于c# - 正则表达式拆分字符串并将括号 [ ] 中的内容放入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19508803/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com