2012-02-18 4 views
0

は、ここで私がやろうとしているものです:正規表現:特定の場所でグループ値を持っていない文字列を選択し

私は次のようになります入力テキスト、持っている:

object("a").style.display="none"; 
object("b").style.display="none"; 
object("c").style.display="none"; 
object("d").style.display="none"; 
object("e").style.display="none"; 
object("g").style.display="block"; 
object("h").style.display="none"; 

.style.display!= "none"(この場合、object( "g")。style.display = "block";)の行をすべて選択します。私は他の価値が何であるかを事前に知らない。

正規表現を使用してこれを行う最良の方法は何ですか?

import re 

text = """ 
any text 
another text 
object("a").style.display="none"; 
object("b").style.display="none"; 
object("c").style.display="none"; 
object("d").style.display="none"; 
object("e").style.display="none"; 
object("g").style.display="block"; 
object("h").style.display="none"; 
""" 

pattern = r"^object\(\"\w+\"\)\.style\.display\=\"(?!none).*?\";$" 

for i in re.findall(pattern, text, re.MULTILINE): 
    print i 

# >> object("g").style.display="block"; 
+0

は、C#プログラムでは、このですか?あなたは本当に正規表現を使う必要がありますか? –

答えて

1

このようなパターンをお探しですか?

object\("[^"]+"\)\.style\.display\="none";(\r\n)?

C#のユニットテスト:

[Test] 
public void Test() 
{ 
    string input = @"object(""a"").style.display=""none""; 
object(""b"").style.display=""none""; 
object(""c"").style.display=""none""; 
object(""d"").style.display=""none""; 
object(""e"").style.display=""none""; 
object(""g"").style.display=""block""; 
object(""h"").style.display=""none"";"; 

    Regex pattern = new Regex(@"object\(""[^""]+""\)\.style\.display\=""none"";(\r\n)?"); 

    string expected = "object(\"g\").style.display=\"block\";\r\n"; 

    string actual = pattern.Replace(input, string.Empty); 

    Assert.AreEqual(expected, actual); 
} 
1

があります:あなたはregex negative lookahead

Pythonの例を使用することができます(申し訳ありませんが、現在入手可能のC#を持っていない)のLINQ &正規表現

var arr = Regex.Matches(myregexstr, @"(object\(""\w+""\)\.style\.display\=)""(\w+)""") 
      .Cast<Match>() 
      .Where(m => m.Groups[2].Value != "none") 
      .Select(m=>m.Groups[0].Value) 
      .ToArray(); 
関連する問題