pryashrma
pryashrma

Reputation: 102

How to find string between two numbers and store it in a array?

The below code is stored in a string named str1, number represents a line number and text represents a php code line. Now, I want to extract the line number and code line separately.

* 47: echo
<http://php.net/echo> echo "<div id=" . $var . ">content</div>"; 
  o 46: $var = htmlspecialchars($v, ENT_QUOTES); 
      + 45: $v = $_SESSION['UserData']; 

Till now, I have tried

str1.Split(new char[] { ':', ';' });

but this also breaks the string from 'http:' and also contains wild char \n \r in the returned array. How do I remove wild char \n \r + o? or Is there any other method to extract Number and String between two numbers?

Upvotes: 0

Views: 117

Answers (2)

Denis
Denis

Reputation: 6082

Regex regex = new Regex(@"(?<LineNumber>\d+)[:](?<Code>.+)$");

using (StreamReader reader = new StreamReader("TextFile1.txt"))
{
    string s = null;

    while ((s = reader.ReadLine()) != null)
    {
        Match match = regex.Match(s);

        if (match.Success)
        {
            Console.WriteLine("{0}: {1}", match.Groups["LineNumber"].Value,
                match.Groups["Code"].Value);
        }
    }
}

Will output:
47: echo
46: $var = htmlspecialchars($v, ENT_QUOTES);
45: $v = $_SESSION['UserData'];

Upvotes: 0

John
John

Reputation: 3702

Try this:

string str1 =  "47: echo <http://php.net/echo> echo \"<div id=\" . $var . \">content</div>\"; " + Environment.NewLine
            + "o 46: $var = htmlspecialchars($v, ENT_QUOTES);" + Environment.NewLine
            + "+ 45: $v = $_SESSION['UserData']; ";

var matches = System.Text.RegularExpressions.Regex.Matches(str1, @"([\d]+)?:(.*)?\r\n?", System.Text.RegularExpressions.RegexOptions.Multiline);
foreach(Match m in matches)
{
    Console.WriteLine(m.Groups[1].Value);
    Console.WriteLine(m.Groups[2].Value);
}

Upvotes: 1

Related Questions