I’m required to do some operations which involve regular expressions.
String I’m operating on:
/dev/fd0 /media/floppy0 auto rw,us
Basically, what I want to do is take the first two parameters (/dev/fd0 and /media/floppy0) and I want to ignore everything after this. To achieve I’ve tried the regular expressions shown below. My question is, why do the following regular expressions produce different results?
Regular expression 1:
grep -o '/dev/f\S*\s*\S*' /etc/fstab
Output (the output that I’m expecting):
/dev/fd0 /media/floppy0
Regular expression 2:
grep -o '/dev/f[\S]*\s*[\S]*' /etc/fstab
Output:
/dev/f
Regular expression 3:
grep -o '/dev/f[^\s]*\s[^\s]*' /etc/fstab
Output:
/dev/fd0 /media/floppy0 auto rw,u
I don’t see why 2 and 3 don’t produce the same output as 1. The way I see it is that for 2, it shouldn’t matter whether I put the non white space short hand character (\S) inside a character class. The same goes for 3. Furthermore, why is 2 different from 3? Isn’t [\S] the same as [^\s]?
I guess I can’t speak to whether they “should” be different — there are many regex engines where your interpretations would be correct — but in POSIX Basic Regular Expressions (BREs; the regex type that
grepuses by default),[\S]is a character class containing\andS, and[^\s]is a character class containing all characters except\ands. (This is per the spec, which requires that, both in BREs and in EREs, “The special characters'.','*','[', and'\'(period, asterisk, left-bracket, and backslash, respectively) shall lose their special meaning within a bracket expression.” [link]) The within-character-class equivalent of\sis[:space:]:Some versions of
grepsupport a nonstandard-Poption to use Perl-compatible regular expressions (PCREs) instead of POSIX regular expressions. Perl-compatible regular expressions do have the behavior you describe, so if yourgrepsupports that option, then you can use it like this: