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

问题描述

| 在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]\\+$\'
亚伯     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...