How to match regex in bash? – Code Example

In this article we will provide you bash script code to match regex. You can match a string against a provided regex. This code could be used to create custom matchers.

Code Example –

This function will return the input value if it matches the regex otherwise null.

#!/bin/bash

regex() {
    [[ $1 =~ $2 ]] && echo "${BASH_REMATCH[1]}"
}

input_data="364"

$(regex "$input_data" '^[0-9]+$') || input_data="56"

echo $input_data

Here we provided a numeric string "364" as input to the regex '^[0-9]+$'. This is the regex for checking if all the characters in the string are digits. If we supply some alphanumeric as input, then regex test will fail and return null. In that case OR condition || will run and value of input will become "56".

Inspired from Dylan Araps

Live Demo

Open Live Demo