Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression [:digit:] and [[:digit]] difference

Tags:

regex

grep

I am currently learning regular expression. I met a problem that I can't find answer on stackoverflow and I hope someone can help find the answer.

I use vim in mac OS system and vim shows the line. If the file "regular_expression.txt" is:

"Open Source" is a good mechanism to develop programs.
You are the No. 1.

Then

grep -n '[:lower:]' regular_expression.txt 

will return

1:"Open Source" is a good mechanism to develop programs.

2:You are the No. 1.

The command

grep '[[:lower:]]' regular_expression.txt 

will return

2:You are the No. 1.

I can't understand the above difference because it seems to me that [:lower:] is a set of lower characters. [[:lower:]] should be the same as [:lower:]. It is also confusing that in the first case where [:lower:] is used, all the lines in the file are returned.

like image 321
essence16 Avatar asked Aug 09 '26 01:08

essence16


1 Answers

POSIX character classes must be wrapped in bracket expressions.

The [:lower:] pattern is a positive bracket expression that matches a single char, :, l, o, w, e or r.

The [[:lower:]] pattern is a positive bracket expression that matches any char that is matched with the [:lower:] POSIX character class (that matches any lowercase letters).

See grep manual:

certain named classes of characters are predefined within bracket expressions... Note that the brackets in these class names are part of the symbolic names, and must be included in addition to the brackets delimiting the bracket expression.

If you mistakenly omit the outer brackets, and search for say, [:upper:], GNU grep prints a diagnostic and exits with status 2, on the assumption that you did not intend to search for the nominally equivalent regular expression: [:epru].

like image 194
Wiktor Stribiżew Avatar answered Aug 11 '26 16:08

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!