在 Bash 正则表达式中,`^` 和 `$` 是指行,还是指整个字符串?

In Bash regular expressions do `^` and `$` refer to lines, or to the entire string?

The Linux Documentation Project (I didn't find details about the regex metacharacters in the Bash manual)中,元字符^$被定义为匹配行:

^: Matches the empty string at the beginning of a line [...]
$: Matches the empty string at the end of a line

然而,当我尝试时,这是不正确的:

$ string="a
> b
> c"

$ [[ $string =~ ^a ]] && echo BOS match
BOS match

$ [[ $string =~ ^b ]] && echo BOL match
# nothing

是手册真的错了,还是我遗漏了什么?

^ 匹配整个输入字符串的开头,$ 匹配 POSIX 正则表达式中整个输入字符串的结尾(Bash 使用 POSIX ERE)。您 link 提到的文档中提到行是因为大多数文本处理工具,如 sedgrepawk 默认情况下逐行读取输入,并且字符串与行一致在大多数情况下。

参见POSIX regex documentation:

9.3.8 BRE Expression Anchoring

A BRE can be limited to matching strings that begin or end a line; this is called "anchoring". The circumflex and dollar sign special characters shall be considered BRE anchors in the following contexts:

  1. A circumflex ( '^' ) shall be an anchor when used as the first character of an entire BRE. The implementation may treat the circumflex as an anchor when used as the first character of a subexpression. The circumflex shall anchor the expression (or optionally subexpression) to the beginning of a string; only sequences starting at the first character of a string shall be matched by the BRE. For example, the BRE "^ab" matches "ab" in the string "abcdef", but fails to match in the string "cdefab". The BRE "(^ab)" may match the former string. A portable BRE shall escape a leading circumflex in a subexpression to match a literal circumflex.

  2. A dollar sign ( '$' ) shall be an anchor when used as the last character of an entire BRE. The implementation may treat a dollar sign as an anchor when used as the last character of a subexpression. The dollar sign shall anchor the expression (or optionally subexpression) to the end of the string being matched; the dollar sign can be said to match the end-of-string following the last character.

  3. A BRE anchored by both '^' and '$' shall match only an entire string. For example, the BRE "^abcdef$" matches strings consisting only of "abcdef".