我正在嘗試解決一個非常簡單的問題 - 在只包含某些字母的陣列中查找字串。但是,我在正則運算式的行為中遇到了一些問題和/或grep我不明白。
#!/usr/bin/perl
use warnings;
use strict;
my @test_data = qw(ant bee cat dodo elephant frog giraffe horse);
# Words wanted include these letters only. Hardcoded for demonstration purposes
my @wanted_letters = qw/a c d i n o t/;
# Subtract those letters from the alphabet to find the letters to eliminate.
# Interpolate array into a negated bracketed character class, positive grep
# against a list of the lowercase alphabet: fine, gets befghjklmpqrsuvwxyz.
my @unwanted_letters = grep(/[^@wanted_letters]/, ('a' .. 'z'));
# The desired result can be simulated by hardcoding the unwanted letters into a
# bracketed character class then doing a negative grep: matches ant, cat, and dodo.
my @works = grep(!/[befghjklmpqrsuvwxyz]/, @test_data);
# Doing something similar but moving the negation into the bracketed character
# class fails and matches everything.
my @fails1 = grep(/[^befghjklmpqrsuvwxyz]/, @test_data);
# Doing the same thing that produced the array of unwanted letters also fails.
my @fails2 = grep(/[^@unwanted_letters]/, @test_data);
print join ' ', @works; print "\n";
print join ' ', @fails1; print "\n";
print join ' ', @fails2; print "\n";
問題:
- 為什么
@works得到了正確的結果卻沒有@fails1呢?該grep檔案建議前者和否定部分perlrecharclass暗示了后者,盡管它使用=~它的例子。這是否與使用有關grep? - 為什么不起作用
@fails2?它與陣列與串列背景關系有關嗎?否則它看起來與減法步驟相同。 - 除此之外,是否有一種純粹的正則運算式方法可以避免減法步驟?
uj5u.com熱心網友回復:
兩者fails都固定于在添加錨^和$和量詞
這些都有效:
my @fails1 = grep(/^[^befghjklmpqrsuvwxyz] $/, @test_data);
my @fails2 = grep(/^[^@unwanted_letters] $/, @test_data);
請記住,/[^befghjklmpqrsuvwxyz]/or/[^@unwanted_letters]/只匹配一個字符。添加 意味著盡可能多。添加^和$表示從字串開頭到結尾的所有字符。
隨著/[@wanted_letters]/邏輯等同于-你是否有一個要的字符(即使字串中不需要的字符)將回傳匹配任何。與/^[@wanted_letters] $/所有字母需要在集合中的位置進行比較,@wanted_letters并且等價于all。
Demo1只有一個字符所以grep失敗了。
Demo2量詞意味著不止一個但沒有錨點 - grep 失敗
Demo3錨點和量詞 - 預期結果。
一旦你了解字符類只匹配一個字符和錨整個字串和量詞的比賽延伸到錨一切,你可以直接只需用想用grep字母:
my @wanted = grep(/^[@wanted_letters] $/, @test_data);
uj5u.com熱心網友回復:
您正在匹配字串中任何字符集之外的內容。但是它仍然可以在字串的其他地方的字符集中包含字符。例如,如果測驗詞是elephant,則否定字符類匹配該a字符。
如果要測驗整個字串,則需要對其進行量化并錨定到末端。
grep(/^[^befghjklmpqrsuvwxyz]*$/, @test_data);
翻譯成英文,就是“詞不包含在集合中的字符”和“詞包含不在集合中的字符”之間的區別。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/349238.html
上一篇:cpanApp::cpanminus失敗并出現多個錯誤:“放棄決議您的/Users/foo/.cpan/sources/modules/02packages.details.txt.gz,錯誤太多”
下一篇:IPCmsgsnd意外等待
