Assume that there is a text which like below:
string str = @"stackoverflow(
stack:stackoverflow)overstackflow(
over:stackoverflow)";
I want to get bold fields. I think I have to find "(" and ":" in text and get the text between of them. Isn't it?
Any advice?
Perhaps with plain string
methods:
IList<String> foundStrings = new List<String>();
int currentIndex = 0;
int index = str.IndexOf("(", currentIndex);
while(index != -1)
{
int start = index + "(".Length;
int colonIndex = str.IndexOf(":", start);
if (colonIndex != -1)
{
string nextFound = str.Substring(start, colonIndex - start);
foundStrings.Add(nextFound);
}
currentIndex = start;
index = str.IndexOf("(", currentIndex);
}
Demo
Look at this post and you can find the answer.
How do I extract text that lies between parentheses (round brackets)?
You only need to do small changes to that regular expression.
string strRegex = @"\((.+?)\:";
RegexOptions myRegexOptions = RegexOptions.None;
Regex myRegex = new Regex(strRegex, myRegexOptions);
string strTargetString = @"stackoverflow(stack:stackoverflow)overstackflow(over:stackoverflow)";
foreach (Match myMatch in myRegex.Matches(strTargetString))
{
if (myMatch.Success)
{
// Add your code here
}
}
I'd go for something like:
Regex matcher = new Regex(@"([^():}]+)\(([^():}]*):([^():}]*)\)");
MatchCollection matches = matcher.Matches(str);
This will look through your input for everything that looks like group1(group2:group3)
. (If any of the groups contains a (
, )
or :
the whole thing will be ignored as it can't figure out what's meant to be where.)
You can then get the matched values as e.g.
foreach(Match m in matches)
{
Console.WriteLine("First: {0}, Second: {1}, Third{2}",
m.Groups[1].Value, m.Groups[2].Value, m.Groups[3].Value);
}
so if you just want the bits between the (
and the :
you can use
foreach(Match m in matches)
{
Console.WriteLine(m.Groups[2].Value);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With