2

Can anyone help me understand why this doesn't work? Just trying out some simple regex in bash.

#!/bin/bash

re="-regex_"

if [[ "$re" =~ ^[-[:alpha:]_]+$ ]]; then
        echo "Regex"

else
        echo "this is not regex"        
fi

Cheers

2
  • On mine it does nothing, no error or anything. Commented Mar 28, 2014 at 20:11
  • 1
    What is your BASH version? Commented Mar 28, 2014 at 20:20

2 Answers 2

2

I am assuming that you are hoping that the "-regex_" will evaluate to true in your if statement.

on the [:alpha:] tag there is nothing to say search for more than one alpha-numeric character.

try

[[ "$re" =~ ^-[[:alpha:]]+_$ ]]
Sign up to request clarification or add additional context in comments.

10 Comments

I've followed you're example and still nothing. I have the permissions set and I'm in the right folder.
did you use the edited one? the first one i posted had a mistake in it... love regexes -_-
I just tried it and still nothing, very strange. Any ideas?
You are having an issue with running bash and not just regex. The comments are right that your original solution should return Regex, my solution has more to do with matching data which starts with - and ends with _. Try looking at your BASH version and see if the syntax you are using is valid. When you run the script it returns "this is not regex" right?
It returns nothing, no error or anything, just moves onto the next line as if nothing happened. BASH version 4.1.2
|
2

If you are having an error running it, make sure you are using unix line endings (run it through dos2unix) and make sure it is marked executable. Otherwise, the script prints "Regex" for me.

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.