lbj-ub
lbj-ub

Reputation: 1423

Regex - Using short hand characters inside a character class

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]?

Upvotes: 1

Views: 813

Answers (1)

ruakh
ruakh

Reputation: 183371

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 grep uses by default), [\S] is a character class containing \ and S, and [^\s] is a character class containing all characters except \ and s. (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 \s is [:space:]:

grep -o '/dev/f[^[:space:]]*\s*[^[:space:]]*' /etc/fstab

Some versions of grep support a nonstandard -P option to use Perl-compatible regular expressions (PCREs) instead of POSIX regular expressions. Perl-compatible regular expressions do have the behavior you describe, so if your grep supports that option, then you can use it like this:

grep -o -P '/dev/f[\S]*\s*[\S]*' /etc/fstab
grep -o -P grep -o '/dev/f[^\s]*\s[^\s]*' /etc/fstab

Upvotes: 2

Related Questions