[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: Question relating regexp



On Fri 17 Jan 2003 15:03:33 +0000(+0100), Robert Land wrote:
> 
> To match a line that starts with a 1, 
> has some digits, at least one space 
> and a name that starts with a K we can write:
> 
> grep '^1[0-9]\{1,\} \{1,\}K' phonelist.txt
> or use * and repeat [0-9] and space:
> grep '^1[0-9][0-9]*  *K' phonelist.txt
> "
> 
> 
> =Why, in the first example, has the author
> prefaced the char 'K' with the one or more
> times multiplier? He only wants to find a 
> name beginning with 'K'(!)

He/she hasn't. The "one or more times multiplier" applies to the preceding element (a space). Let's break this regular expression down:

^		matches start of line
1		matches a '1'
[0-9]\{1,\}	matches one or more digits
 \{1,\}		matches one or more spaces
K		matches a 'K'


> 
> Then, in the snd grep command he doubled
> '[0-9]', wouldn't only '^1[0-9]*....'be 
> sufficent? Again, 'K' is prefaced with the
> asterisk which doesn't seem necessary to me.

Again, the asterisk applies to the preceding, not following, element.


The example can be written more simply with egrep:
egrep '^1[0-9]+ +K' phonelist.txt
+ means one or more of the preceding element. It's extended regular expression syntax. See "man 7 regex" for basic vs. extended regular expressions.

I hope this helps.

-- 
Cheers,
Clive



Reply to: