I have a string like this:
{abc}@{defgh}mner{123}
How can I get all strings between {
and }
as an array or list?
Like this:
{ {abc},{defgh},{123} }
I have a string like this:
{abc}@{defgh}mner{123}
How can I get all strings between {
and }
as an array or list?
Like this:
{ {abc},{defgh},{123} }
using Regex is a good choice
string str = "{abc}@{defgh}mner{123}";
foreach (Match match in Regex.Matches(str,"{[^}]+}"))
{
Console.WriteLine(match.Value);
}
Using sites like RegExr, you can easily try your regex before using it in code:
string str = "{abc}@{defgh}mner{123}";
foreach (Match match in Regex.Matches(str,"(\{.+?\})"))
{
Console.WriteLine(match.Value);
}
var input = "{abc}@{defgh}mner{123}";
var pattern = @"\{(.+?)\}";
var matches = Regex.Matches(input, pattern);
IList<string> output = new List<string>();
foreach (Match match in matches)
output.Add(match.Groups[0].Value);
Simple Version
var input = "{abc}@{defgh}mner{123}";
var pattern = @"\{(.+?)\}";
var matches = Regex.Matches(input, pattern);
IList<string> output = matches.Cast<Match>().Select(x => x.Groups[0].Value).ToList();
output.Dump();
You can use Regex
var str = "{abc}@{defgh}mner{123}";
var regex = new Regex(@"({\w+})",RegexOptions.Compiled);
var result = regex.Matches(str).Cast<Match>().Select(x=>x.Value);
result is IEnumerable<string>
as required in OP
Output (value of Result)
{abc}
{defgh}
{123}
Using Regex and turning them into a list using LINQ
var l = new Regex(@"\{(\w+)\}")
.Matches("{abc}@{defgh}mner{123}l")
.Cast<Match>()
.Select(m => m.Groups[0].Value)
.ToList();
How it works:
The regex {(\w+)} means:
This will find all the text between the curly brackets
The regex will give a MatchCollection
We have to use Cast to turn it into something linq can query
We .Select items from the collection, m is an individual item, m.Groups[0].Value is the text captured by the group, between the curly brackets
.ToList returns all the texts in one list
You can try following code, it doesn't uses regular expressions, so you don't need to know it!
static void Main(string[] args)
{
string s = "{abc}@{defgh}mner{123}";
int i1, i2 = 0;
while ((i1 = s.IndexOf('{', i2)) >= 0)
{
i2 = s.IndexOf('}', i1);
// Here you can add Substring result to some list or assign it to a variable...
Console.WriteLine(s.Substring(i1 + 1, i2 - i1 - 1));
}
}
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"{([A-Za-z0-9\-]+)}" ;
string input = "{abc}@{defgh}mner{123}";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
Console.WriteLine();
}
}
Output :
abc
defgh
123
You can check the Online Execution of the code : http://tpcg.io/uuIxo1