Solved

# Bash Regular expression

Posted on 2010-09-16
Medium Priority
814 Views
The result of the following match is successful. Why?
x=12345 ; [[ \$x =~ ^[0-9]{3} ]] && echo 3 digits

I thought I wanted only 3 digits.  So to me it should have failed.  I was only expecting it to work for x=123.

Please explain.  Also if I want to match only 3 digits, what would be the regular expression?
0
Question by:farzanj
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points

LVL 3

Expert Comment

ID: 33696246
Are you saying it echoed "12345"?  It echoed 5 digits?
0

LVL 6

Accepted Solution

DalHorinek earned 1000 total points
ID: 33696331
You need to

[[ \$x =~ ^[0-9]{3}\$ ]]

Because otherwise it matches 3 numbers on the begining and then there can be anything ...

\$ says that there can't be anything else.
0

LVL 4

Assisted Solution

Tachion earned 800 total points
ID: 33696359
The reason it also works on 12345 (and 123abc for that matter) is that you only specify a match for the first 3 characters of the string to be numbers. You don't say "nothing may come after".

The following DOES work:

x=1234 ; [[ \$x =~ ^[0-9]{3}\$ ]] && echo 3 digits

The \$ says, "nothing more".
0

LVL 33

Assisted Solution

pgnatyuk earned 200 total points
ID: 33696571
x=123 ; [[ \$x = [0-9][0-9][0-9] ]] && echo 3 digits

says "3 digits" for '123' and not for '1234' or '12'.

I'm late. But I think, this is the simplest variant - nothing to explain, everything's clear
0

LVL 31

Author Comment

ID: 33696739
0

LVL 31

Author Comment

ID: 33702007
I think due change of interface, I had awarded points but it did not go through.  Please open it again so that I can award points.  Thanks.
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.