Tejender Mohan
Tejender Mohan

Reputation: 45

Why aren't these regexes working as expected?

When I run these commands, I get output like this:

Screenshot of Terminal

Here are the commands and output, in textual form:

$ cat exte
i
ii
iii
iiii
iiiii
iiiiii

This works fine:

$ egrep --color i\{4,5\} exte
iiii
iiiii
iiiiii

I guess it should show color only one or two "i" of a line, but the output colors everything:

$ egrep --color i\{1,2\} exte

i
ii
iii
iiii
iiiii
iiiiii

Similarly, I can't see the extended regex working here:

$ egrep --color i? exte
i
ii
iii
iiii
iiiii
iiiiii


$ egrep --color i+ exte
i
ii
iii
iiii
iiiii
iiiiii

Upvotes: 0

Views: 55

Answers (1)

user5076313
user5076313

Reputation:

This command colors all, because in your file have that many i's.

$ egrep --color i\{1,2\} exte
i
ii
iii
iiii
iiiii
iiiiii

Take the example of third line in output. You didn't specified any constraint for a line matching starting of the line or ending of the line. So, it matches one by one. So, the first two i's in the second third line is matched. For the third i it checks the condition, that time also the condition is true. So, it matches all.

If you want more clear output you can use the -o option to what are all matching.

-o:-

Print only the matched (non-empty) parts of a matching line, with each such part on a separate output line.

$ egrep --color i? exte

The ? mark in grep regular expression, it matches zero or one occurrence of the preceding character. So, It is also working like the above command. All the i's matching one by one for the regex.

$ egrep --color i+ exte 

The + means match one or more occurrence of the preceding character. So, it matches all the i's for line by line for a single occurrence.

If you want to see the output as clear format you have to use the -o option.

Upvotes: 1

Related Questions