Using Regular Expressions in JQ
Here we will explore how to use regular expressions in JQ with functions like test
, match
, split
, and sub
.
We'll go through examples of each function to demonstrate their use.
1. Testing a Pattern: test
Suppose you have the following JSON input:
If you want to check if the string contains the word "hello", you can use the test
function:
This will produce the following output:
You can also make the test case-insensitive:
Try this example in our JQ Playground.
2. Extracting Matches: match
Next, let's extract a specific part of a string using the match
function. Suppose your JSON input looks like this:
If you want to extract the domain from the email, you can do so with the following filter:
This will produce the following output:
Try this example in our JQ Playground.
3. Splitting a String: split
Now let's see how you can split a string into parts. Suppose your JSON input is:
If you want to split this string into an array of fruits, you can use the split
function:
This will produce the following output:
Try this example in our JQ Playground.
4. Substituting a Pattern: sub
You can use the sub
function to replace part of a string with another value. For example, suppose your JSON input is:
If you want to replace the first -
with a /
, you can do so with:
This will produce the following output:
Try this example in our JQ Playground.
5. Global Substitution: gsub
If you want to replace all occurrences of a pattern, you can use gsub
. For example, to replace all dashes with slashes in this input:
You can do the following:
This will produce the following output:
Try this example in our JQ Playground.