简体   繁体   中英

Matching optional slash in regex

I need a regex that matches first two words between three "/" characters in url: eg. in /en/help/test/abc/def it should match /en/help/.

I use this regex: /.*?/(.*?)/ however sometimes I have the url without the last slash like /en/help which does not match because of the missing last slash.

Can you help me to adjust the regex to match only "/en/help" part? Thanks

A simple way to solve it is to replace reluctant (.*?)/ with greedy ([^/]*) :

/.*?/([^/]*)

This would stop at the third slash if there is one, or at the end of the string if the final slash is not there.

Note that you could replace .*? with the same [^/]* expression for consistency:

/[^/]*/([^/]*)

If characters will contain alphanumeric, then you can use the following pattern:

static void Main(string[] args)
{
    string s1 = "/en/help/test/abc/def";
    string s2 = "/en/help ";
    string pattern = 
        @"(?ix)   #Options
          /       #This will match first slash
          \w+     #This will match [a-z0-9]
          /       #This will match second slash
          \w+     #Finally, this again will match [a-z0-9] until 3-rd slash (or end)";
    foreach(string s in new[] { s1, s2})
    {
        var match = Regex.Match(s, pattern);
        if (match.Success) Console.WriteLine($"Found: '{match.Value}'");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM