Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
Extracting Port Number from a localhost API Request to a Server using Regular Expressions
Next article icon

Describe the procedure of extracting a query string with regular expressions

Last Updated : 24 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

A query string is a part of a URL that follows a question mark (?) and is used to pass data to a web page or application. It is typically composed of key-value pairs that are separated by an ampersand (&). The key represents the parameter and the value represents the data that is being passed through the parameter.

In this article, we will discuss how to extract a query string from a URL using regular expressions.

Approach:

First, we need to define a regular expression pattern that will match the query string of a URL. A regular expression is a sequence of characters that forms a search pattern. It can be used to check if a string contains the specified search pattern.
The regular expression pattern for a query string is: 

[?&]([^=]+)(=([^&#]*))?

This pattern matches the beginning of the query string (?), followed by any key-value pairs separated by an ampersand (&). The key is captured in the first capturing group ([^=]+), and the value is captured in the third capturing group (([^&#]*)).

Next, we can use the RegExp object in JavaScript to create a regular expression from the pattern. We can do this by passing the pattern to the RegExp constructor as follows: 

const pattern = '[?&]([^=]+)(=([^&#]*))?'; const regex = new RegExp(pattern);

Once we have the regular expression, we can use the test() method to check if the query string of a URL matches the pattern. The test() method returns a boolean value indicating whether the string contains a match or not.

Example 1: The following code is using JavaScript to extract the query string from a given URL by matching it against a regular expression pattern, and logs the query string to the console if it matches.

C++
#include <iostream> #include <regex> #include <string>  using namespace std;  int main() {     // URL to be queried     string url = "https://example.com?key1=value1&key2=value2";      // Regular expression pattern     string pattern = "[?&]([^=]+)(=([^&#]*))?";      // Creating a regex object from the pattern     regex regexObj(pattern);      // Creating a match object to hold the matched substring     smatch match;      // Querying the string using the regex     if (regex_search(url, match, regexObj)) {         string queryString = match.str();         cout << queryString << endl;     }      return 0;  } 
Java
import java.util.regex.Matcher; import java.util.regex.Pattern;  public class Main {     public static void main(String[] args)     {         // url to be queried         final String url             = "https:example.com?key1=value1&key2=value2";          // pattern         final String pattern = "[?&]([^=]+)(=([^&#]*))?";          // building regex from the pattern         Pattern regex = Pattern.compile(pattern);          // querying the string using the regex         Matcher matcher = regex.matcher(url);         if (matcher.find()) {             String queryString = matcher.group();             System.out.println(queryString);         }     } } 
JavaScript
<script>     // url to be queried     const url = 'https://example.com?key1=value1&key2=value2';      // pattern     const pattern = '[?&]([^=]+)(=([^&#]*))?';      // building regex from the pattern     const regex = new RegExp(pattern);      // querying the string using the regex     if (regex.test(url)) {       const queryString = url.match(regex)[0];       console.log(queryString);        } </script> 
C#
using System; using System.Text.RegularExpressions;  class Program {   static void Main(string[] args)   {     // url to be queried     const string url = "https://example.com?key1=value1&key2=value2";      // pattern     const string pattern = @"[?&]([^=]+)(=([^&#]*))?";      // building regex from the pattern     Regex regex = new Regex(pattern);      // querying the string using the regex     if (regex.IsMatch(url))     {       string queryString = regex.Match(url).Value;       Console.WriteLine(queryString);     }   } } 
Python
import re  # URL to be queried url = "https://example.com?key1=value1&key2=value2"  # Regular expression pattern pattern = r"[?&]([^=]+)(=([^&#]*))?".encode('unicode-escape').decode()  # Creating a regex object from the pattern regex_obj = re.compile(pattern)  # Querying the string using the regex match = regex_obj.search(url) if match:     query_string = match.group()     print(query_string) # This code is contributed by Prajwal Kandekar 

Output
?key1=value1

Example 2: This code is using JavaScript to extract the query parameters from a given URL by matching it against a regular expression pattern, then it splits the query string into individual key-value pairs. It iterates over the key-value pairs and stores them in an object, finally, it logs the query parameters object to the console.

JavaScript
<script>      // Define the URL and the regular expression pattern     const url = 'https://example.com?key1=value1&key2=value2';     const pattern = '[?&]([^=]+)(=([^&#]*))?';      // Create the regular expression object     const regex = new RegExp(pattern);      // Check if the URL matches the pattern     if (regex.test(url)) {        // Extract the query string from the URL        const queryString = url.match(regex)[0];         // Split the query string into individual key-value pairs        const keyValuePairs = queryString.split('&');         // Iterate over the key-value pairs      // store them in an object        const queryParams = {};        keyValuePairs.forEach(pair => {         const [key, value] = pair.split('=');         queryParams[key] = value;       });         // Output the query parameters object       console.log(queryParams);    } </script> 

Output
{ '?key1': 'value1' }

Example 3: This code is using JavaScript to extract the query parameters from a given URL by matching it against a regular expression pattern, then it splits the query string into individual key-value pairs, then it iterates over the key-value pairs, and stores them in an object. Finally, it iterates over the query parameters object and outputs each key-value pair in the console.

JavaScript
<script>      // Define the URL and the regular expression pattern     const url = 'https://example.com?key1=value1&key2=value2';     const pattern = '[?&]([^=]+)(=([^&#]*))?';      // Create the regular expression object     const regex = new RegExp(pattern);      // Check if the URL matches the pattern     if (regex.test(url)) {           // Extract the query string from the URL           const queryString = url.match(regex)[0];          // Split the query string into individual key-value pairs        const keyValuePairs = queryString.split('&');       // Iterate over the key-value pairs       // store them in an object      const queryParams = {};      keyValuePairs.forEach(pair => {         const [key, value] = pair.split('=');         queryParams[key] = value;       });        // Iterate over the query parameters object      // output each key-value pair     for (const [key, value] of Object.entries(queryParams)) {         console.log(`${key}: ${value}`);       }   }  </script> 

Output
?key1: value1

In conclusion, extracting a query string from a URL using regular expressions is a useful technique for parsing and manipulating data passed through a URL. By defining a regular expression pattern that matches the query string of a URL and using the RegExp object and the test() method, we can easily extract the query string and split it into individual key-value pairs. These key-value pairs can then be stored in an object for easy access, allowing us to easily retrieve and manipulate the data passed through the query string. Regular expressions are a powerful tool for working with strings, and this technique can be useful in a variety of web development scenarios.


Next Article
Extracting Port Number from a localhost API Request to a Server using Regular Expressions

P

phasing17
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2022
  • regular-expression
  • JavaScript-Questions

Similar Reads

  • Extracting all present dates in any given String using Regular Expressions
    Given a string Str, the task is to extract all the present dates from the string. Dates can be in the format i.e., mentioned below: DD-MM-YYYYYYYY-MM-DDDD Month YYYY Examples: Input: Str = "The First Version was released on 12-07-2008.The next Release will come on 12 July 2009. The due date for paym
    6 min read
  • Extracting all Email Ids in any given String using Regular Expressions
    Given a string str, the task is to extract all the Email ID's from the given string. Example: Input: "Please send your resumes to Hr@[email protected] for any business inquiry please mail us at business@[email protected]"Output: Hr@[email protected]@[email protected] Appr
    4 min read
  • Extracting PAN Number from GST Number Using Regular Expressions
    Given a string str in the form of a GST Number, the task is to extract the PAN Number from the given string. General Format of a GST Number: "22AAAAA0000A1Z5" 22: State CodeAAAAA0000A: Permanent Account Number (PAN)1: Entity Number of the same PANZ: Alphabet Z by default5: Checksum digit Examples: I
    4 min read
  • SQL Data Extraction with Regular Expressions
    Regular expressions (RegEx) are a powerful mechanism for matching patterns in text, allowing us to extract specific characters, validate input, and search for patterns. In SQL, regular expressions are used in queries to validate data, extract specific substrings, or search for matching patterns in c
    5 min read
  • Extracting Port Number from a localhost API Request to a Server using Regular Expressions
    Given a String test_str as localhost API Request Address, the task is to get the extract port number of the service. Examples: Input: test_str = ‘http://localhost:8109/users/addUsers’Output: 8109Explanation: Port Number, 8109 extracted. Input: test_str = ‘http://localhost:1337/api/products’Output: 1
    5 min read
  • Extracting Repository Name from a Given GIT URL using Regular Expressions
    Given a string str, the task is to extract Repository Name from the given GIT URL. Examples: GIT URL can be any of the formats mentioned below: Input: str="git://github.com/book-Store/My-BookStore.git"Output: My-BookStoreExplanation: The Repo Name of the given URL is: My-BookStore Input: str="git@gi
    4 min read
  • Perl - Use of Capturing in Regular Expressions
    A regular expression or a regex is a string of characters that define the pattern that we are viewing. It is a special string describing a search pattern present inside a given text. Perl allows us to group portions of these patterns together into a subpattern and also remembers the string matched b
    3 min read
  • Extracting a String Between Two Other Strings in R
    String manipulation is a fundamental aspect of data processing in R. Whether you're cleaning data, extracting specific pieces of information, or performing complex text analysis, the ability to efficiently work with strings is crucial. One common task in string manipulation is extracting a substring
    3 min read
  • How to Validate SQL Query With Regular Expression?
    Regular expressions (RegEx) are a powerful tool for pattern matching, commonly used for validating data in SQL queries. In SQL, regular expressions help validate complex data types such as email addresses, phone numbers, alphanumeric strings, and numeric values. While front-end validation is essenti
    5 min read
  • Escaped Periods in R Regular Expressions
    Regular expressions (regex) are a powerful tool for pattern matching and text manipulation in R. Understanding how to use special characters, such as the period (.), is crucial for crafting accurate and effective regular expressions. In this article, we will focus on the role of escaped periods in R
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences