2012-08-28 32 views
0

我有一個小問題。我嘗試編寫一個函數來提取C#中的東西(我必須將正則表達式從PHP轉換爲C#)。在C#中的正則表達式(來自PHP的正則表達式)

我一般寫這樣的:

public static class ExtensionMethods 
{ 
    public String PregReplace(this String input, string[] pattern, string[] replacements) 
    { 
    for (var i = 0; i < pattern.Length; i++) 
    { 
     input = Regex.Replace(input, pattern[i], replacements[i]); 
    } 

    return input; 
    } 
} 

但是我有這些例子中的問題(在PHP代碼)

preg_replace('@<head[^>]*?>.*?</head>@siu', ' ', $result); 
preg_replace('@</?((frameset)|(frame)|(iframe))@iu', "\n\$0", $result);   

但是當我使用在C#這個regulax表達

String[] pattern = new String[2]{"@<head[^>]*?>.*?</head>@siu", "@</?((frameset)|(frame)|(iframe))@iu"}; 
String[] replace = new String[2]{" ", "\n\$0"}; 
input.PregReplace(pattern , replace); //my new function 

我沒有任何輸入差異(我沒有捕捉正則表達式)。 你能幫我一下我的功能嗎?我在正則表達式中有錯誤嗎?

編輯: 我改變代碼:

String[] pattern = new String[2]{"<head[^>]*?>.*?</head>", "</?((frameset)|(frame)|(iframe))"}; 
String[] replace = new String[2]{" ", "\n\\$0"}; 

input = "input = "><head><title>something</title></head><body>sdegsehgaeg<frame>aggsd</frame></"; 
string s = input.PregReplace(pattern, replace); 

在回答我得到

> <body>sdegsehgaeg 
\<frame>aggsd 
\</frame></ 

> <body>sdegsehgaeg\n\\<frame>aggsd\n\\</frame></ 

這只是爲了多字符\爲\ n \ $ 0如果我改變\ n \ $ 0的\ n \ $ 0 I得到錯誤(urecognized轉義序列)

好吧,我解決的問題(\ N $ 0)

謝謝你的幫助。

+0

我以前要求repolace函數,它不回答你的正則表達式相關的問題,但[這裏很好的答案](http://stackoverflow.com/a/9600320/704144)可以爲你提供一個替代方案。 –

+0

現在應該有一個替換。你是否像這樣使用它? string s = input.PregReplace(pattern,replace);請記住,該函數正在返回一個NEW字符串。 – oopbase

回答

1

刪除代碼中的@,刪除和iu後的最後一個@。在PHP中,你需要這些修飾符,如果需要,你可以在C#中調用一些RegexOptions

+1

您也可以使用[this site](http://regexhero.net/tester/)來檢查語法。我認爲還有其他人,但我覺得這對C#很有用。 – Nashibukasan