Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't this regular expression test working? [duplicate]

Tags:

regex

bash

shell

I have this

echo $line
Thisisaline.

I was wondering why is this not working:

if [[ "$line" =~ "[a-zA-Z]+\.$" ]] ; then echo "hello"; fi

Above regex gives no output.

like image 877
Ankur Agarwal Avatar asked May 01 '11 02:05

Ankur Agarwal


People also ask

Why is not working in regex?

You regex doesn't work, because you're matching the beginning of the line, followed by one or more word-characters (doesn't matter if you use the non-capturing group (?:…) here or not), followed by any characters.

How do you match duplicate words in regex?

Following example shows how to search duplicate words in a regular expression by using p. matcher() method and m. group() method of regex. Matcher class.

How do you validate a regular expression?

To validate a RegExp just run it against null (no need to know the data you want to test against upfront). If it returns explicit false ( === false ), it's broken. Otherwise it's valid though it need not match anything.


1 Answers

The problem is that you are using quotes...

In bash regex, there is no need for quotes, and moreso, they should not be used (unless you are trying to match a quote (in which case you can escape it \")... Also if you want a space in your pattern, you must escape it, (there is a space after the back-slash ...

Also note, that to match the entire line as being alphabetic, you must add a leading ^ and a trailing $, otherwise it will match such lines as: 123 456 abc. cat and mouse

like image 162
Peter.O Avatar answered Oct 12 '22 15:10

Peter.O