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?

2
  • s[1+2] how will regex perfomr arithmatic operations...how will it detect a linear increase in numbers? Commented Nov 14, 2014 at 6: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. Commented Nov 14, 2014 at 6:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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+)+$
1

How about a regex like

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

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

Comments

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

Try this.See demo.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.