2015-04-03 45 views
1

我正在創建一個將處理url的應用程序,此url將有多個段(此段的名稱可以有特殊字符),此過程將使用超過1000000網址。從URL中刪除字符,但使用正則表達式排除一個字

我不能用分開的方式替換每個段的特殊字符,因爲這會使過程變慢。我們的想法是加入的URL的所有段{ - }或{0}和過程在一個單一的call.The完整的URL我將取代{ - }用/

{-}Lake Havasu City{-}Kingman-area{-}Lake Ha/vasu City{-}North Pointe-by-Read Homes{-}hola{*e}s!fsd3$^gdfg% 

我有這樣的規律表達嘗試獲得特殊字符,但排除特殊字

(?:(?<!")\{\-\}(?!"))|[^0-9a-zA-Z\s] 

我得到的特殊字符與這部分[^ 0-9A-ZA-Z \ S],但我不能使表達式忽略{ - }

enter image description here

var url = @"{-}Lake Havasu City{-}Kingman-area{-}Lake Ha/vasu City{-}North Pointe-by-Read Homes{-}hola{*e}s!fsd3$^gdfg%"; 
var newUrl = RemoveSpecialCharacters(url).Replace("{-}","/") 

public static string RemoveSpecialCharacters(string input) 
{ 
    Regex r = new Regex("(?:(?<!")\{0\}(?!"))|[^0-9a-zA-Z\s]", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); 
    return r.Replace(input, " "); 
} 

而結果必須是:

{-}Lake Havasu City{-}Kingman area{-}Lake Ha vasu City{-}North Pointe by Read Homes{-}hola e s fsd3 gdfg 

感謝

+0

謝謝你的問題,一個非常好的! – 2015-04-03 19:53:45

回答

0

您可以使用這樣的正則表達式:

(\{-\})|([\w\s]+)|\W 

Working demo

並替換內容無線th \1\2。你可以看到在置換部的輸出結果:

enter image description here

+0

當我將它轉換爲C#不工作時 var re = @「/(\ { - \})|([\ w \ s] +)| \ W/g」; var str = @「{ - }哈瓦蘇湖城{ - }金曼地區{ - }哈哈湖/瓦蘇城{ - }北角Pointe-by-Read Homes { - } hola {* e} s!fsd3 $^gdfg %「; var subst = @「\ 1 \ 2」; var r = new Regex(re); var result = r.Replace(str,subst); – 2015-04-03 16:48:31

+0

@ user3334335會發生什麼?什麼是錯誤? – 2015-04-03 17:09:19

+0

錯誤是顯而易見的:'re' var肯定是在JavaScript中,而不是C#。 – 2015-04-03 17:20:22

1

我想我終於固定你的正則表達式。看看:我加{-!檢查連字符是否正確匹配花括號外{}(非常感謝去Regex Best Trick)。正則表達式(將與IgnoreCase選項一起使用)是:

[^0-9a-z\s{}-]|\{(?!\-\})|(?<!\{\-)\}|((?<!\{)?)\-(?(1)(?!\})) 

總的來說:我添加{}-到否定字符類,所以我們不首先檢查他們,然後我加3層的替代品,我可以檢查上下文中的3個符號。最困難的部分是檢查一下大括號內是否有連字符,並且可以使用條件表達式和捕獲組在外觀後面...... Mind-breaking :)

這裏是代碼:

var InputText = @"{-}Lake Havasu City{-}Kingman-area{-}Lake Ha/vasu City{-}North Pointe-by-Read Homes{-}hola{*e}s{-!fsd3$^gdfg%"; 

var MyRegex = new Regex(@"[^0-9a-z\s{}-]|\{(?!\-\})|(?<!\{\-)\}|((?<!\{)?)\-(?(1)(?!\}))", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); 

var clean_str = MyRegex.Replace(InputText, string.Empty); 

輸出:

{-}Lake Havasu City{-}Kingmanarea{-}Lake Havasu City{-}North PointebyRead Homes{-}holaesfsd3gdfg 

enter image description here

+0

真的很好,謝謝你的幫助 – 2015-04-06 03:21:02

+0

我們的答案在第一步中取得了同樣的結果:'{ - }哈瓦蘇湖城{ - }金馬納雷亞{ - }哈瓦蘇湖市{ - }北部PointebyRead家{ - } holaesfsd3gdfg',唯一的區別是您用'$ 1 ',而我的需要一個空的替換字符串。 – 2015-04-17 10:11:14

0

這是最近,我得到的,是不完整的完美,但工作

var re = @"(\{-\})|([^0-9a-zA-Z\s]+)"; 
var str = @"{-}Lake Havasu City{-}Kingman-area{-}Lake Ha/vasu City{-}North Pointe-by-Read Homes{-}hola{*e}s!fsd3$^gdfg%"; 
var subst = @"$1 "; 
var r = new Regex(re, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); 
var result = r.Replace(str, subst).Replace("{-} ","/"); 
相關問題