Describe the procedure of extracting a query string with regular expressions
Last Updated :
28 Apr, 2025
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
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>
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.
Similar Reads
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
4 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
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
Working with Regular Expressions in PostgreSQL Regular expressions, often referred to as "regex," are patterns used to match strings. In PostgreSQL, regular expressions allow us to search, validate, and manipulate text data in a powerful way. Regular expressions are helpful whether we need to find patterns in a string, replace parts of a text, o
5 min read