且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

BASH正则表达式匹配-在方括号中包含要匹配的字符列表中的方括号?

更新时间:2022-12-28 14:39:58

好,这是我第一次听说=~运算符,但这是我通过反复试验发现的内容:

Ok, this is the first time I've heard of the =~ operator but nevertheless here's what I found by trial and error:

if [[ $newfile =~ ^(.*)([-[:space:][]*(what|ever)[][:space:]-]*)(.*)$ ]] 
                          ^^^^^^^^^^              ^^^^^^^^^^

看起来很奇怪,但实际上确实可以工作(刚刚测试过).

Looks strange but actually does work (just tested it).

编辑
引用Linux手册页regex(7):

EDIT
Quote from the Linux man pages regex(7):

要在列表中包含文字],请使其成为第一个字符(在可能的^之后).要包括文字-,使其成为范围的第一个或最后一个字符,或第二个端点.要将文字aq-aq用作范围的第一个端点,请将其括在"[."中.和.]"作为整理元素(请参见下文).除了这些以及使用aq [aq的某些组合(请参阅下一段)之外,所有其他特殊字符(包括aq \ aq)在方括号表达式中都失去其特殊意义.

To include a literal ] in the list, make it the first character (following a possible ^). To include a literal -, make it the first or last character, or the second endpoint of a range. To use a literal aq-aq as the first endpoint of a range, enclose it in "[." and ".]" to make it a collating element (see below). With the exception of these and some combinations using aq[aq (see next paragraphs), all other special characters, including aq\aq, lose their special significance within a bracket expression.