Adil
Adil

Reputation: 2538

How this regular expression is working

I found a script which has the following snippet:-

userid=`expr "\`id\`" : ".*uid=[0-9]*(\(.[0-9a-z]*\)) .*"`

It returns the userid.

When i tried to learn how it is doing:-

#id
#uid=11008(adilm) gid=1200(cvs),1400(build)

So I realized that (.[0-9a-z]*) is matching the userid. But if I placed like below:

#userid=`expr "uid=11008(ADILM) gid=1200(cvs),1400(build)" : ".*uid=[0-9]*(\(.[0-9a-z]*\)) .*"`
#echo $userid
ADILM

It works. As per my understanding '.' is matching to ADILM. But when i removed '.' like below:-

#userid=`expr "uid=11008(ADILM) gid=1200(cvs),1400(build)" : ".*uid=[0-9]*(\([0-9a-z]*\)) .*"`
#echo $userid
ADILM

It still works how? We have only provided lowercase letters but its still working.

Upvotes: 1

Views: 280

Answers (2)

ghostdog74
ghostdog74

Reputation: 342373

this will not explain the regex, but alternative ways to get your id.

$ id -u -n

$ id|sed 's/uid=[0-9]*(//;s/).*//'

Upvotes: 0

Peter Kofler
Peter Kofler

Reputation: 9440

  • The subexpression (\(.[0-9a-z]*\)) matches a group containing the brackets plus the user id.
  • The dot inside this regex matches only the first character and all others need to be lowercase or numeric anyway.
  • So obviously the regex here is not case sensitive (i option) per default. As your username is only [a-z0-9] it still matches.
  • I don't think the dot makes sense. Are there any valid usernames not starting with a letter? The dot is here to make sure the username is at least one character long.
  • Better might be (\([0-9a-z]+\)) then.

Upvotes: 3

Related Questions