开发者

Regular expression Modification

I have one asp.net application, in which i have one text box for URL. And i am using the regular expression for validating. My regular expression is like this:^(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$

But now i have one enhancement like the text always开发者_开发问答 keeps the text of http://. at that time the validation of this expression have to ignore the default text (http://). How it possible? Please help me by resolving this issue.


Your expression matches the http:// part, so it "keeps" that part of the match. If the text box you're validating doesn't contain that part at all, simply drop (ht|f)tp(s?)\:\/\/ from your regex.

If it is part of the text box, but you want to ignore it after having matched it, then you can put capturing parenthesess around your intended match. Your original regex would then look like this:

^(ht|f)tp(s?)\:\/\/([0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?)$

Now the part without http:// or ftp:// etc will be in backreference number 3.

That said, your regex as it stands now is pretty bad and also incorrect (lots of unnecessary escapes, unnecessary parentheses, wrongly constructed character classes (URLs with port number will fail here), and I'm pretty sure that you don't want & in there)...

It is not easy to validate URLs with regexes. What are your intentions? What should be valid, what shouldn't be?


You can try this -

Use ((ht|f)tp(s?)\:\/\/)? in the starting of your regular expression which makes http:// or ftp:// as optional.

Your complete regex would be -

^((ht|f)tp(s?)\:\/\/)?[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&%\$#_]*)?$
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜