1

Why is this INCREDIBALLY simple REGEX not matching?!!?

#!/bin/bash
    while true
        do
            read -r -p $'What is the JIRA Ticket associated with this work?' JIRA
            #Use a regular expresion to verify that our reply stored in JIRA is only 4 digits, if not, loop and try again.
            if [[ ! "$JIRA" =~ [0-9]{4} ]]
                then
                    echo -en "The JIRA Ticket should only be 4 digits\nPlease try again."
                    continue
                else
                    break 1
            fi
        done

When prompted, if you type "ffffff" it catches, but if you type more than 4 digits "444444" or even toss a letter in there "4444444fffff" it catches nothing, hits the else block and quits. I think this is basic and I'm dumbfounded as to why its not catching the extra digits or characters?

I appreciate the help.

3 Answers 3

4

You need to change your equality test to:

if [[ ! "$JIRA" =~ ^[0-9]{4}$ ]]

This ensures that the entire string contains just four digits. ^ means beginning of string, $ means end of string.

Sign up to request clarification or add additional context in comments.

1 Comment

I've been writing advanced BASH now, for about a year ... how have I never come across this?!!? It worked, and solved my problem, so thank you for that ... maybe I've just hit blind luck every time before. Thanks for helping me learn something new!!!
3

The regular expression is open-ended, meaning it only has to match a substring of the left-hand argument, not the entire thing. Anchor your regular expression to force it to match the entire string:

if [[ ! "$JIRA" =~ ^[0-9]{4}$ ]]

Comments

0

Maybe a simpler pattern (== instead of =~) may solve your issue:

#!/bin/bash
while true
do
    read -r -p $'What is the JIRA Ticket associated with this work?' JIRA
    [[ $JIRA == [0-9][0-9][0-9][0-9] ]] && break 1
    echo -en "The JIRA Ticket should only be 4 digits\nPlease try again."
done

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.