1

Uisng regex in c# i want to extract page value from last anchor tag? This is the code:

<nav class="pagination shop">
            <ul><div id="results_bottom"><li style="display: inline-block;"><a class="btn current"  href="?swift=&country=india&bank=&page=1">1</a> <a class="btn"  href="?swift=&country=india&bank=&page=2">2</a> <a class="btn"  href="?swift=&country=india&bank=&page=3">3</a> <a class="btn"  href="?swift=&country=india&bank=&page=4">4</a> <a class="btn"  href="?swift=&country=india&bank=&page=5">5</a> <a class="btn"  href="?swift=&country=india&bank=&page=6">6</a> <a class="btn"  href="?swift=&country=india&bank=&page=7">7</a> <a class="btn"  href="?swift=&country=india&bank=&page=8">8</a> <a class="btn"  href="?swift=&country=india&bank=&page=9">9</a> <a href="?swift=&country=india&bank=&page=2">Next &rarr;</a><a href="?swift=&country=india&bank=&page=193">Last &raquo;</a></li></div></ul></nav>

"What I need is "193" from

<a href="?swift=&country=india&bank=&page=193">Last &raquo;</a>

Thanks in adavnce

  • You should take a look at Html Agility Pack library. Then you can parse HTML like XML and use xpath etc – Jurion Apr 02 '16 at 16:27

1 Answers1

2

Querystring can have page in 2 different ways

  1. ?swift=&country=india&bank=&page=193
  2. ?page=193&country=india&bank=&swift=

In this way, page=193 can have ? or & in the beginning. Following regex would work for both cases.

        int pageNo = 0;
        var matches = Regex.Matches("?swift=&country=india&bank=&page=193", @"&page=[0-9]*|\?page=[0-9]*");
        if (matches.Count > 0)
        {
            foreach (var match in matches)
            {
                int.TryParse(match.ToString().Substring("?page=".Length), out pageNo);
            }
        }

You have to extract ?page=193 or ?page=193 whichever is matched then extract int part and parse it to pageNo, a local integer variable.

M.S.
  • 4,283
  • 1
  • 19
  • 42
  • Thanks a lot Mahesh! Can u please tell me what if I iterate through mutliple anchor tags as in my example and want to get value of "page" of last anchor tag because i have different page values of last tag for different countries? – waqasqureshi Apr 02 '16 at 17:49