2
echo [18%] | sed s:[\[%\]]::g

[18%]同じ正確なパターンがvimで正常に置き換えられるため、私はこれに本当に混乱しています。[また、いくつかのオンライン正規表現ツールで式をテストしましたが、それらはすべて、 、%、および]で意図したとおりに一致すると言っています。-rオプションを追加して、置換コマンドを引用符で囲んでみました。

このタスクを達成するために使用できる他のコマンドがあることは知っていますが、sed をよりよく理解できるように、なぜこのように動作するのかを知りたいです。

4

1 に答える 1

6
$ echo [18%] | sed s:[][%]::g
18

sed は POSIX.2 正規表現構文をサポートします。デフォルトでは基本 (BRE) 構文、-rフラグを使用した拡張構文です。POSIX.2 構文 (基本または拡張) では、文字クラスの最初の文字にすることで、右角かっこを含めます。バックスラッシュは役に立ちません。

他のほとんどすべての最新の言語とツールが Perl または Perl に似た正規表現構文を使用しているため、これは面倒です。POSIX 構文は時代錯誤です。

POSIX.2 構文については、regex(7) のマニュアル ページを参照してください。

 A bracket expression is a list of  characters  enclosed  in  "[]".   It  normally
 matches  any  single character from the list (but see below).  If the list begins
 with '^', it matches any single character (but see below) not from  the  rest  of
 the  list.  If two characters in the list are separated by '-', this is shorthand
 for the full range of characters between those two (inclusive) in  the  collating
 sequence,  for  example, "[0-9]" in ASCII matches any decimal digit.  It is ille‐
 gal(!) for two ranges to share an endpoint, for  example,  "a-c-e".   Ranges  are
 very  collating-sequence-dependent, and portable programs should avoid relying on
 them.

 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 '-' 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  '['  (see  next  para‐
 graphs), all other special characters, including '\', lose their special signifi‐
 cance within a bracket expression.
于 2015-08-28T00:50:57.000 に答える