How to combine the second occurrence of a string with a regular expression?

I have a URL like this

http://www.abc.com/h/x/y

and I want to parse "x / y" from it with a regex. I use the following regex

h/(?<Group>[\s\S]*?)\s*?/

But it matches only "x", but I want "x / y". I can find the second occurrence of "/" using a programming language and then parse it, but I want to do this only from a regular expression.

Please, help.

-1
source share
3 answers

I would not use a regex, but simply:

var url = "http://www.abc.com/h/x/y";
var ix1 = url.LastIndexOf('/');
var ix2 = url.LastIndexOf('/', ix1 - 1);
var part = url.Substring(ix2 + 1);

This is understandable without explaining the complex regex :)

(+ checking if a valid URL can be executed separately before the actual parsing)

0
source

URL-, , . h ?

, , - :

http://(?:[a-z\d\-]+\.)*[a-z\d]+/h/(.*)
  • (http://), , .
  • ((?:[a-z\d\-]+\.)*) * () TLD, . ( ). IP, IP-.
  • [a-z\d]+ TLD - - (, localhost). , IP , .
  • ((.*)) , /h/.

:

  • IPv6 IP- . . , , .
  • URL-, http://--some-weird.--.com/h/1/2/3.
0

I have a much simpler solution. Please do a string length check check. This is a quick layout.

    string myString = @"http://www.microsoft.com/products/surface/order/pay.aspx";
    char charToFind = '/';
    int nthOccuranceToFind = 4;
    int startIndex = -1;
    int nthPosOfCharToFind = 0;

    while (nthOccuranceToFind > 0)
    {
        int findIndex = startIndex + 1;
        startIndex = myString.IndexOf(charToFind, findIndex);
        --nthOccuranceToFind;
    }

    //startIndex here will contain index of nth occurance.
0
source

All Articles