Is it possible to exclude only query parameters from the URL string using regular expressions while leaving hash?

Asked 1 years ago, Updated 1 years ago, 84 views

For example, if there is a URL like this
https://www.example.com/test/?q=test&s=test
https://www.example.com/hoge/?q=foo&s=faa#hoge

I would like to exclude only query parameters and extract the following URL and hash.
https://www.example.com/test/
https://www.example.com/hoge/#hoge

Is it possible to do this in a regular expression?
I would appreciate your advice.

regular-expression

2022-09-30 17:51

1 Answers

  • # does not appear except for fragment initiation
  • The first ? before
  • # starts the query
    • However, ? may appear in queries or fragments
  • However, ? may appear in queries or fragments

With this property, regular expression replacement will be easy to achieve.For example,

^([^?)#]*)(\?[^#]*)?(#.*)?$

If you leave the first and third groups in this regular expression, it will be the desired behavior.

RFC 3986 contains the regular expression for the URI.I think it will be helpful.

^([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
       12            3  4          5       6  7        8 9

Also, some programming languages have libraries that express URLs/URIs, so using them may be easier to understand than using regular expressions.


2022-09-30 17:51

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.