Ezz Redfox
Ezz Redfox

Reputation: 99

Getting the int value using RegEx

So i have a string and i wanted to get the int value on Param8, i tried using Regex expression

(< Param8>)\d+(< /Param8>)

but i only want the value inside of it.

<Param1>13</Param1>
<Param2>Print Document</Param2>
<Param3>username</Param3>
<Param4>\\PC</Param4>
<Param5>HP DeskJet 1110 series</Param5>
<Param6>USB001</Param6>
<Param7>123</Param7>
<Param8>1</Param8>

How do i get the int value only of the last param? because when i tried the above expression, it also included the param tag.

edit: here's my code

private void getPrintedPages()
{
    Regex parts = new Regex(@"<Param8>\d+</Param8>");

    StreamReader reader = File.OpenText(@".\report.xml");
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Match match = parts.Match(line);
        if (match.Success)
        {
            string result = match.Groups[1].Value.ToString();

            MessageBox.Show(result);
        }
    }
}

Upvotes: 0

Views: 121

Answers (1)

Oleksii Klipilin
Oleksii Klipilin

Reputation: 1936

You need to use groups in regex

static void Main(string[] args)
{
    string input = "<Param8>1</Param8>";

    Regex rx = new Regex(@"<Param8>(\d+)</Param8>");
    var res = rx.Match(input);

    Console.WriteLine(res.Groups[1].Value);
}

No need to use groups () for your open/close tags, add group only for your digit and get it. Zero group is always whole result, so you need the first one.

Upvotes: 1

Related Questions