2012-04-24 31 views
2

我有這樣的格式的字符串。我想匹配在開始時沒有abcd的字符串。如果不包含某種模式,我如何匹配所有內容?

abcd.efgh.ijkl 
pqrs.efgh.ijkl 
xyz.efgh.ijkl 

我想出了這個表達式(?<!abcd).efgh.ijklhttp://rubular.com/r/jyZMIJxoNz

還挺做什麼,我需要的。它匹配pqrs.efgh.ijklxyz.efgh.ijkl.efgh.ijkl部分,並忽略abcd.efgh.ijkl。但我也希望它匹配pqrsxyz部件。

我試圖做這樣一個條件像這樣(?(?<!abcd)|.*\.efgh.ijkl)但它甚至不被識別爲正則表達式。語法有什麼問題? ?這豈不是說:「如果它開始與ABCD然後blank其他匹配一切都交給.efgh.ijkl

+1

@juergend:不是。 '^'是「起始行」錨點,所以'^(abcd)'將匹配以'abcd'開始的任何內容。 – 2012-04-24 10:00:35

+0

哪種語言? – noob 2012-04-24 10:01:37

回答

0

試試這個:

(?m)^(?!abcd).+$

說明:

<!-- 
(?m)^(?!abcd).+$ 

Options:^and $ match at line breaks 

Match the remainder of the regex with the options:^and $ match at line breaks (m) «(?m)» 
Assert position at the beginning of a line (at beginning of the string or after a line break character) «^» 
Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!abcd)» 
    Match the characters 「abcd」 literally «abcd» 
Match any single character that is not a line break character «.+» 
    Between one and unlimited times, as many times as possible, giving back as needed (greedy) «+» 
Assert position at the end of a line (at the end of the string or before a line break character) «$» 
--> 
0

試試這個一個:

[^"(a.+b)|(b.+c)|(c.+d)|"].* 

http://rubular.com/r/51OShSXwUz

+0

不完全。 '[^「(a。+ b)|(b。+ c)|(c。+ d)|」]'相當於'[^ ad「()|。+]' - 這是一個否定[character class ](http://www.regular-expressions.info/charclass.html),它匹配除'a','b','c','d','''','(',')以外的任何單個字符',''''''''或'+'。 – 2012-04-24 16:32:05

0

負lookbehinds很有趣,他們是一個很好用的工具。

但如果你只想匹配整行不以abcd開始,一個簡單的方法做,這是匹配開始與abcd線,再取每行匹配。

示例(Python):

In [1]: lines = [ 
    ...: "abcd 1", 
    ...: "abcd 2", 
    ...: "pqrs 3", 
    ...: "pqrs 4" ] 

In [2]: import re 

In [4]: for line in lines: 
    ...:  if re.match(r"^abcd.+$", line): 
    ...:   pass # do nothing 
    ...:  else: 
    ...:   print (line) 
    ...: 

pqrs 3 
pqrs 4 

此外,如果你正在尋找的abcd是一個字符串(即字面abcd,而不是一些其他的正則表達式),那麼字符串操作會更快更容易理解:

In [5]: for line in lines: 
    ...:  if not(line.startswith('abcd')): 
    ...:   print(line) 
    ...: 

pqrs 3 
pqrs 4 
1

你想爲此使用一個前瞻,而不是向後看。

^(?!abcd\.)[a-z]+(?:\.[a-z]+)+$ 

主要正則表達式是^[a-z]+(?:\.[a-z]+)+$,其包括由點分隔的字母兩個或更多個團塊的字符串匹配。起始錨點之後的前視確保第一個叢不是abcd

注意的是,如果它真的紅寶石你在做這個,^$錨。這意味着正則表達式會從字符串中抽取第二行:

foo 
pqrs.efgh.ijkl 
bar 

......這可能不是您想要的。爲了確保你只用Ruby匹配整個字符串,你應該使用字符串錨,\A\z

\A(?!abcd\.)[a-z]+(?:\.[a-z]+)+\z 

至於你嘗試使用條件,紅寶石似乎並不支持他們。但沒關係,反正也不行。

相關問題