正则表达式-在字符类中使用速记字符 [英] Regex - Using short hand characters inside a character class

查看:75
本文介绍了正则表达式-在字符类中使用速记字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要执行一些涉及正则表达式的操作.

I'm required to do some operations which involve regular expressions.

我正在处理的字符串:

/dev/fd0        /media/floppy0  auto    rw,us

基本上,我想做的是采用前两个参数(/dev/fd0/media/floppy0),此后我想忽略所有内容.为了实现这一点,我尝试了如下所示的正则表达式.我的问题是,为什么以下正则表达式会产生不同的结果?

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?

正则表达式1:

grep -o '/dev/f\S*\s*\S*' /etc/fstab

输出(我期望的输出):

Output (the output that I'm expecting):

/dev/fd0        /media/floppy0

正则表达式2:

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

输出:

/dev/f

正则表达式3:

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

输出:

/dev/fd0        /media/floppy0  auto    rw,u

我不明白为什么2和3不会产生与1相同的输出.我的看法是,对于2,是否放置非空白简写字符()在字符类中. 3也一样.此外,为什么2与3不同? [\S][^\s]不同吗?

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

推荐答案

我想我不能说他们是否应该"有所不同—在很多正则表达式引擎中,您的解释都是正确的—但是在POSIX基本正则表达式(BRE;默认为grep使用的正则表达式类型)中,[\S]是包含\S的字符类,而[^\s]是包含除\s. (这是根据规范的要求,在BRE和ERE中均要求特殊字符'.''*''[''\'(句号,星号,左括号和反斜杠,分别在括号表达式中将失去其特殊含义."[链接])\s的字符级内等效项是[:space:]:

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

某些版本的grep支持非标准的-P选项,以使用与Perl兼容的正则表达式(PCRE)代替POSIX正则表达式.兼容Perl的正则表达式确实具有您描述的行为,因此,如果您的grep支持该选项,则可以这样使用它:

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

这篇关于正则表达式-在字符类中使用速记字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆