Home > Enterprise >  Regular expression to match path in bash condition
Regular expression to match path in bash condition

Time:03-05

I'm looking to write a regular expression to match the following paths.

puts/push/1234/request
puts/push/57689/request
puts/push/123/request
puts/push/4567/request
puts/push/34/request

Have a variable name Targetpath and any of the above path could be it's value. I have the following conditional expression to perform the match.

if [[ $Targetpath =~ puts/push/*/request ]]; then echo 1; else echo 0; fi

But the match is not happening and getting 0 echod to the terminal always

How the above command should be modified to perform the correct match.

CodePudding user response:

Try using the following regex string, modify the number of numerals if needed

regex="puts\/push\/[0-9]{2,}\/request"
if [[ $var =~ $regex ]]; then echo 1; else echo 0; fi

CodePudding user response:

If you plan to match any text but / in place of your * you can use

if [[ $Targetpath =~ puts/push/[^/] /request ]];

Note that [^/] is a negated bracket expression that matches one or more (since in POSIX ERE is a one or more quantifier) chars other than a / char.

Or, if you intend to match digits where your * is:

if [[ $Targetpath =~ puts/push/[0-9] /request ]];

Here, [0-9] (or [[:digit:]] ) matches one or more digits.

Here is a quick demo:

#!/bin/bash
Targetpath='puts/push/1234/request'
rx='puts/push/[0-9] /request'
if [[ "$Targetpath" =~ $rx ]]; then echo 1; else echo 0; fi
# => 1

Note you do not need to escape slashes in this case as / are not regex delimiters here (in sed commands, you need to escape / if / is used as a regex delimiter char).

In case you do not care what char appear between puts/push/ and /request, simply use glob matching:

if [[ "$Targetpath" == puts/push/*/request ]]; then echo 1; else echo 0; fi

Note the == operator and * that matches any text. However, note that glob patterns match the whole text/string, so you might need * on both ends of it, too.

CodePudding user response:

As I commented this requirement doesn't need regex. It can be done entirely in glob (or extglob):

Case 1: If you want to validate starting and ending part only then use:

[[ $Targetpath == puts/push/*/request ]]

Case 2: If you want to validate starting and ending part and allowing only digits in the middle part:

# enable extended glob
shopt -s extglob 
[[ $Targetpath == puts/push/ ([[:digit:]])/request ]]

Case 3: If you want to validate starting and ending part and allowing only 1 of any non-/ characters the middle part:

# enable extended glob
shopt -s extglob 
[[ $Targetpath == puts/push/ ([!/])/request ]]
  • Related