Validate URL query string with regex

前端 未结 6 2054
南笙
南笙 2020-12-06 03:00

I\'m trying to validate a query string with regex. Note that I\'m not trying to match out the values, but validate its syntax. I\'m doing this to practice regex, so I\'d app

6条回答
  •  情书的邮戳
    2020-12-06 03:27

    This seems to be what you want:

    ^\?([\w-]+(=[\w-]*)?(&[\w-]+(=[\w-]*)?)*)?$
    

    See live demo

    This considers each "pair" as a key followed by an optional value (which maybe blank), and has a first pair, followed by an optional & then another pair,and the whole expression (except for the leading?) is optional. Doing it this way prevents matching ?&abc=def

    Also note that hyphen doesn't need escaping when last in the character class, allowing a slight simplification.

    You seem to want to allow hyphens anywhere in keys or values. If keys need to be hyphen free:

    ^\?(\w+(=[\w-]*)?(&\w+(=[\w-]*)?)*)?$
    

提交回复
热议问题