For example, I have this string :
string myString="abc {string 1} def {string 2}{string 3}";
I need to get an array of strings with :
string 1
string 2
string 3
or
{string 1}
{string 2}
{string 3}
Is there any easy way to do this?
答案 0 :(得分:2)
Use regex. This is the search you would want to preform:
{.+?}
For example:
string input = "abc {string 1} def {string 2}{string 3}";
string pattern = "{.+?}";
Regex rgx = new Regex(pattern, RegexOptions.IgnoreCase);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0)
{
Console.WriteLine("{0} ({1} matches):", input, matches.Count);
foreach (Match match in matches)
Console.WriteLine(" " + match.Value);
}
yields
abc {string 1} def {string 2}{string 3} (3 matches):
{string 1}
{string 2}
{string 3}
答案 1 :(得分:0)
这是一个LINQ解决方案:
string myString="abc {string 1} def {string 2}{string 3}";
string[] result = myString.Split('{')
.Where(x => x.Contains("}"))
.Select(x => new string(x.TakeWhile(c => c != '}').ToArray()))
.ToArray();
<强>结果:强>
result[0]="string 1"
result[1]="string 2"
result[2]="string 3"