Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting specific part of text in a strict text

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?

like image 932
Stack User Avatar asked Dec 20 '12 09:12

Stack User


4 Answers

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

like image 187
Tim Schmelter Avatar answered Nov 16 '22 23:11

Tim Schmelter


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.

like image 41
Dimitar Avatar answered Nov 17 '22 01:11

Dimitar


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
  }
}
like image 1
David Brabant Avatar answered Nov 17 '22 00:11

David Brabant


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);
}
like image 1
Rawling Avatar answered Nov 17 '22 00:11

Rawling