2010-12-08 27 views
4

使用Perl風格的正則表達式,是否有可能尋找某些不是特定模式的東西?如何使用正則表達式來尋找某些模式的東西

例如,[^abc]尋找單個字符不是a也不是b也不是c

但我可以指定比單個字符更長的東西嗎?
例如,在下面的字符串中,我想要搜索不是頂級域名的第一個單詞,它不包含大寫字母,或者可能包含一些更復雜的規則,如3-10個字符。在我的例子,這應該是"abcd"

net com org edu ABCE abcdefghijklmnoparacbasd abcd 

回答

5

可以使用負前瞻斷言做到這一點:

^(?!(?:net|com|org|edu)$)(?!.*[A-Z])[a-z]{3,10}$ 

See it

說明:

^     - Start anchor 
$     - End anchor 
(?:net|com|org|edu) - Alternation, matches net or com or org or edu 
(?!regex)   - Negative lookahead. 
         Matches only if the string does not match the regex. 

所以部分(?!(?:net|com|org|edu)$)確保輸入不是最高級別之一el域名。

該部分(?!.*[A-Z])確保輸入沒有大寫字母。

的部分[a-z]{3,10}$確保輸入的長度是ATLEAST 3和atmost 10

+0

有一個偉大的視頻,解釋一下aheads(和其他一些基本的正則表達式)位置:http://net.tutsplus.com/tutorials/other/how-to-use-lookaheads-and-lookbehinds-in-your-regular-expressions/ – Haroldo 2010-12-08 11:36:04

+0

更好地使用補碼代替`.`:`(?![^ AZ] * [AZ])``。 – Gumbo 2010-12-08 12:21:04

4

只需使用「不匹配」運算符:〜!

所以您只需建立表達式,然後看到一個變量不符合它:

if ($var !~ /abc/) { 
    ... 
} 
0

恕我直言,它更容易做一些匹配正則表達式和一些與Perl檢查。

#!/usr/bin/env perl 

use strict; 
use warnings; 

my $s = "net com org edu ABCE abcdefghijklmnoparacbasd abcd"; 

# loop short words (a-z might not be what you want though) 
foreach($s =~ /(\b[a-z]{3,10}\b)/g){ 
    print $_, "\n" if is_tpl($_); 
} 

順便說一句,有很多頂級域名..