微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在字符类中使用加号作为正则表达式的一部分?

如何解决如何在字符类中使用加号作为正则表达式的一部分?

| 在cygwin中,这不会返回匹配项:
$ echo \"aaab\" | grep \'^[ab]+$\'
但这确实返回一个匹配项:
$ echo \"aaab\" | grep \'^[ab][ab]*$\'
aaab
这两个表达式是否不相同? 有没有什么方法可以表达“字符类中的一个或多个字符”而无需两次键入字符类(例如在秒示例中)? 根据此链接,两个表达式应该相同,但也许Regular-Expressions.info并不涵盖cygwin中的bash。     

解决方法

grep
具有多个“模式”匹配,并且默认情况下仅使用一个基本集合,除非将其转义,否则它不会识别许多元字符。您可以将grep设置为扩展或perl模式,以评估
+
。 从
man grep
Matcher Selection
  -E,--extended-regexp
     Interpret PATTERN as an extended regular expression (ERE,see below).  (-E is specified by POSIX.)

  -P,--perl-regexp
     Interpret PATTERN as a Perl regular expression.  This is highly experimental and grep -P may warn of unimplemented features.


Basic vs Extended Regular Expressions
  In basic regular expressions the meta-characters ?,+,{,|,(,and ) lose their special meaning; instead use the backslashed versions \\?,\\+,\\{,\\|,\\(,and \\).

  Traditional egrep did not support the { meta-character,and some egrep implementations support \\{ instead,so portable scripts should avoid { in grep -E patterns and should use [{] to match a literal {.

  GNU  grep -E attempts to support traditional usage by assuming that { is not special if it would be the start of an invalid interval specification.  For example,the command grep -E \'{1\' searches for the two-character string {1 instead of reporting a syntax
       error in the regular expression.  POSIX.2 allows this behavior as an extension,but portable scripts should avoid it.
或者,您可以使用
egrep
代替
grep -E
。     ,  在基本正则表达式中,元字符
?
+
{
|
(
)
  失去其特殊的意义;而是使用反斜杠版本\\ ?,   
\\+
\\{
\\|
\\(
\\)
。 因此,请使用反斜杠版本:
$ echo aaab | grep \'^[ab]\\+$\'
aaab
或激活扩展语法:
$ echo aaab | egrep \'^[ab]+$\'
aaab
    ,用反斜杠屏蔽,或将egrep扩展为grep,别名为
grep -e
echo \"aaab\" | egrep \'^[ab]+$\'
亚伯
echo \"aaab\" | grep \'^[ab]\\+$\'
亚伯     

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。