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:

"hello world"

If you want to check if the string contains the word "hello", you can use the test function:

. | test("hello")

This will produce the following output:

true

You can also make the test case-insensitive:

. | test("hello"; "i")

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:

"user@example.com"

If you want to extract the domain from the email, you can do so with the following filter:

. | match("@([a-zA-Z0-9.-]+)"; "g").captures[0].string

This will produce the following output:

{
  "domain": "example.com"
}

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:

"apple, banana, cherry"

If you want to split this string into an array of fruits, you can use the split function:

. | split(", ")

This will produce the following output:

[
  "apple",
  "banana",
  "cherry"
]

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:

"2024-10-10"

If you want to replace the first - with a /, you can do so with:

. | sub("-"; "/")

This will produce the following output:

"2024/10-10"

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:

"2024-10-10"

You can do the following:

. | gsub("-"; "/")

This will produce the following output:

"2024/10/10"

Try this example in our JQ Playground.

See other online JQ resources

JQ PlaygroundJQ interactive tutorialJQ cheatsheetContact Strings with JQ