views:

44

answers:

4

What Regex do I need for match this url:

Match:

1234
1234/
1234/article-name

Don't match:

1234absd
1234absd/article-name
1234/article.aspx
1234/any.dot.in.the.url
+1  A: 
^\d+(/?)|(/[a-zA-Z-]+)$

That may work. or not. Hope it helps

bwawok
The problem here is that `()` has a special meaning in IIS7 url rewriting. I'm looking for a way to escape them.
stacker
A: 

http://gskinner.com/RegExr/

Good tool to regular expression testing and to learn.

James
A: 

Hope this ll help u ........

        string data = "1234/article-name";
        Regex Constant = new Regex("(?<NUMBERS>([0-9]+))?(//)?(?<DATA>([a-zA-Z-]*))?");
        MatchCollection mc;
        mc = Constant.Matches(data,0);
        if (mc.Count>0)
        {
            for (int l_nIndex = 0; l_nIndex < mc.Count; l_nIndex++)
            {
                string l_strNum = mc[l_nIndex].Groups["NUMBERS"].Value;
                string l_strData = mc[l_nIndex].Groups["DATA"].Value;
            }
        }
+1  A: 

You can try:

^\d+(?:\/[\w-]*)?$

This matches a non-empty sequence of digits at the beginning of the string, followed by an optional suffix of a / and a (possibly empty) sequence of word characters (letters, digits, underscore) and a -.

This matches (see on rubular):

1234
1234/
1234/article-name
42/section_13

But not:

1234absd
1234absd/article-name
1234/article.aspx
1234/any.dot.in.the.url
007/james/bond

No parenthesis regex

You shouldn't need to do this, but if you can't use parenthesis at all, you can always expand to alternation:

^\d+$|^\d+\/$|^\d+\/[\w-]*$
polygenelubricants
Thanks for the link.
stacker
@stacker: Rubular is nice. If you have any problem with the regex, just link me to your rubular test and explain what didn't go as expected, etc, and I'll help you find the more specific regex for your need.
polygenelubricants