sample.txt
含む
abcde
abde
次のコマンドの出力を誰かが説明できますか?
grep '[[ab]]' sample.txt
-出力なしgrep '[ab[]]' sample.txt
-出力なしgrep '[ab[]' sample.txt
-出力はabcde
、abde
grep '[ab]]' sample.txt
-出力なし
そして、どういう[(ab)]
意味[^(ab)]
ですか?[ab]
と同じ[^ab]
ですか?
最初に理解しておくべきことは、文字クラス内では、正規表現のメタ文字はどれも特別な意味を持たないということです。それらは文字通り一致します。たとえば、an*
は a に一致し、繰り返し*
を意味しません。0 or 1
同様に、()
は と に一致(
し)
、 は作成しませんcapture group
。
文字クラスでa が見つかった場合、]
文字クラスは自動的に閉じられ、それ以降の文字はその文字クラスの一部ではなくなります。さて、上記で何が起こっているかを理解しましょう:
1
、2
、およびでは4
、キャラクター クラスは最初の終了時に終了します]
。したがって、最後の閉じ括弧 - ]
, は文字クラスの一部ではありません。個別に合わせる必要があります。したがって、パターンは次のようになります。
'[[ab]]' is same as '([|a|b)(])' // The last `]` has to match.
'[ab[]]' is same as '(a|b|[)(])' // Again, the last `]` has to match.
'[ab]]' is same as '(a|b|])(])' // Same, the last `]` has to match.
^
^---- Character class closes here.
現在、両方の文字列]
の末尾に no がないため、一致は見つかりません。
一方、3 番目のパターンでは、文字クラスは最後の]
. したがって、すべてが文字クラス内にあります。
'[ab[]' means match string that contains 'a', or 'b', or '['
これは完全に有効で、両方の文字列に一致します。
[(ab)]
ととはどういう[^(ab)]
意味ですか?
[(ab)]
(
、 、a
、b
のいずれかに一致することを意味し)
ます。文字クラス内では、正規表現のメタ文字に特別な意味がないことに注意してください。したがって、文字クラス内にグループを作成することはできません。
[^(ab)]
の正反対を意味し[(ab)]
ます。指定された文字を含まない任意の文字列に一致します。
[ab]
と同じ[^ab]
ですか?
(
いいえ。これらの 2 つには と は含まれません)
。したがって、それらは少し異なります。
私はそれを試してみます:
grep '[[ab]]' - match string which has one of "[,a,b" and then a "]" char followed
grep '[ab[]]' - match string which has one of "a,b,[" and then a "]" char followed
grep '[ab[]' - match string which has one of "a,b,["
grep '[ab]]' - match string which has one of "a,b" and then a "]" char followed
grep '[(ab)]' - match string which has one of "(,a,b,)"
grep '[^(ab)]' - match string which doesn't contain "(,a,b" and ")"
grep '[ab]' - match string which contains one of "a,b"
grep '[^ab]' - match string which doesn't contain "a" and "b"
grep
この例では、これらのコマンドを実行できます。
#create a file with below lines:
abcde
abde
[abcd
abcd]
abc[]foo
abc]bar
[ab]cdef
a(b)cde
あなたは違いを見て、私のコメント/説明でそれについて考えます.