0

I'm trying to come up with a Regex expression that I can use with Javascript .test to make sure my system is only accepting query strings in a valid format.

The format looks like this i=1&s1=122&s2=238&s3=167&s4=756&s5=13 It can have an unlimited number of s#= arguments in it, so could be longer or shorter than this example.

In English the format is something like i=1&s[1+0]=[any number > 0]&s[1+1]=[any number > 0]&s[1+2]=[any number > 0] and so on.

Right now the regex I have is /^([\w-]+(=[\w-]*)?(&[\w-]+(=[\w-]*)?)*)?$/ It's based on the code provided in this answer. It does an ok job of rejecting some types of invalid strings, but there are still a lot that slip through.

How can I improve this regex expression so it more accurately rejects invalid data?

Community
  • 1
  • 1
Ectropy
  • 1,533
  • 4
  • 20
  • 37
  • `s[1+2]` how will regex perfomr arithmatic operations...how will it detect a linear increase in numbers? – vks Nov 14 '14 at 06:20
  • If it can't that's fine. The system isn't super picky about what the keys in the key-value pairs are. I was just indicating the format in case it is possible. – Ectropy Nov 14 '14 at 06:22

3 Answers3

2

If I understand the question correctly, you can tighten things up with:

/^i=1(&s\d+=\d+)+$/

It will allow, say, s14 to come before s2, but query parameters are supposed to be unordered anyway.

Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • I think this is the best one, because it correctly maintains that the string begins with `i=1`. I made one change, since I don't need a capturing group. Final regex expression used: `^i=1(?:&s\d+=\d+)+$` – Ectropy Nov 14 '14 at 06:34
1

How about a regex like

^i=\d+(?:&s\d+=\d+)+$

For example http://regex101.com/r/rP8vU5/2

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
1
^i=\d+(?:&s\d+=\d+(?=&|$))+$

Try this.See demo.

http://regex101.com/r/pQ9bV3/14

vks
  • 67,027
  • 10
  • 91
  • 124