Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If statement regex in bash with plus operator

I'm sure this is a simple oversight, but I don't see it, and I'm not sure why this regex is matching more than it should:

#!/bin/bash
if [[ $1 =~ ([0-9]+,)+[0-9]+ ]]; then
{
  echo "found list of jobs"
}
fi

This is with input that looks like "02,48,109,309,183". Matching that is fine

However, it is also matching input that has no final number and is instead "09,28,34,"

Should the [0-9]+ at the end dictate the final character be at least 1+ numbers?

like image 654
J M Avatar asked Apr 13 '13 17:04

J M


People also ask

What does plus do in regex?

A regular expression followed by a plus sign ( + ) matches one or more occurrences of the one-character regular expression. If there is any choice, the first matching string in a line is used. A regular expression followed by a question mark ( ? ) matches zero or one occurrence of the one-character regular expression.

What is A+ in regular expression?

The character + in a regular expression means "match the preceding character one or more times". For example A+ matches one or more of character A. The plus character, used in a regular expression, is called a Kleene plus . Regular Expression.

What is Bash if [- N?

A null string in Bash can be declared by equalizing a variable to “”. Then we have an “if” statement followed by the “-n” flag, which returns true if a string is not null. We have used this flag to test our string “name,” which is null.

How do you do if statements in regex?

If the if part evaluates to true, then the regex engine will attempt to match the then part. Otherwise, the else part is attempted instead. The syntax consists of a pair of parentheses. The opening bracket must be followed by a question mark, immediately followed by the if part, immediately followed by the then part.


2 Answers

You have to add markers for beginning (^) and end ($) of input:

#!/bin/bash
if [[ $1 =~ ^([0-9]+,)+[0-9]+$ ]]; then
    echo "found list of jobs"
fi

Otherwise it matches 09,28,34, because it matches from 0 until 4, ignoring everything that follows.

like image 112
speakr Avatar answered Sep 19 '22 08:09

speakr


Your regex only has to match somewhere in the string, not from start to end. To make it match the whole string, use the ^ and $ meta-characters:

#!/bin/bash
if [[ $1 =~ ^([0-9]+,)+[0-9]+$ ]]; then
  echo "found list of jobs"
fi

(Incidentally, you don't need { and } to define a block in Bash, that's the job of then and fi)

like image 42
IMSoP Avatar answered Sep 21 '22 08:09

IMSoP