1

I'm trying to validate an url without domain, just the path and params.

The regular expression that I'm using do most of the work, but It has some errors that I dont know how to prevent (I'm pretty noob with regexp):

/^(\/([\w#!:.?+=&%@!\-\/])+)$/i

The next example are correctly validated

/asd.jsp -> true
/asd/asd.jsp -> true
/asd/asd.jsp?bar=baz&inga=42&quux -> true
/asd/asd.jsp?bar=ba z&inga=42&quux -> false

But this ones arent correct ulrs and them gives me true too:

/asd/asd./jsp -> true :(
/asd/asd.jsp/ -> true :(
/asd./asd.jsp -> true :(
/asd///asd.jsp -> true :(
/asd/asd.jsp&bar=baz?inga=42?quux -> true :(

Do you recommend to use a function instead of a regex?

Very much thanks!

Masta
  • 169
  • 2
  • 15
  • Take a look to [this question](http://stackoverflow.com/questions/161738/what-is-the-best-regular-expression-to-check-if-a-string-is-a-valid-url). Just remove regex for the domain (search the 3rd dot). – Adriano Repetti Jul 13 '12 at 12:08
  • 1
    `/asd/asd.jsp/` is a valid url – Ωmega Jul 13 '12 at 12:09

2 Answers2

1

Try this:

^(\\/\\w+)+\\.\\w+(\\?(\\w+=[\\w\\d]+(&\\w+=[\\w\\d]+)+)+)*$

I already escaped special characters, so you can directly use it in java. By the way, /asd/asd.jsp?bar=baz&inga=42&quux is not a valid URL.

Unescaped Regex:

^(\/\w+)+\.\w+(\?(\w+=[\w\d]+(&\w+=[\w\d]+)+)+)*$
M. Abbas
  • 6,073
  • 4
  • 30
  • 40
  • I have changed your solution a bit to allow the value "/asd/asd.jsp" and just one parameter with "?": `^(\/\w+)+\.\w+(\?(\w+=[\w\d]+(&\w+=[\w\d]+)*)+){0,1}$` As a last request, is possible to allow too the values "/asd/" and "/asd"? Very much thanks for your solution, is really great! – Masta Jul 13 '12 at 15:25
  • in javascript not working it has a bug , if length of the string is even it shows false@M. Abbas – Arun karthi Mani Jun 08 '19 at 22:04
1
^(\/\w+)+(\.)?\w+(\?(\w+=[\w\d]+(&\w+=[\w\d]+)*)+){0,1}$

VALID:

/test
/test/test
/test.jsp
/test.jsp?v=1
/test.jsp?v=1&v=2
/test/test.jsp?v=1&v=2

INVALID:

/test/test./jsp
/test/test.jsp/
/test./test.jsp
/test///test.jsp
Camila S.
  • 11
  • 1