2017-08-08 20 views
1

輸入This AbT5xY\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\nmangoUvW testC#正則表達式 - 匹配特定的字符串後面是substring1或substring2

繼正則表達式給出了輸出:This SomeFruitUvW is a test SomeFruitUvW is a test and AbT5xrAppleUvW and another SomeFruitUvW test.

Regex.Replace(st, "AbT5xY\\s*(Apple)|(mango)", "SomeFruit"); 

但我需要的是,如果AbT5xY之後Apple然後用Fruit1代替AbT5xYApple;並且如果AbT5xY之後是mango,則用Fruit2替換AbT5xYmango。因此,

所需的輸出This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test.

注意AbT5xY和蘋果或AbT5xY和芒果之間

  1. 我忽略空格字符(換行,空格,製表符等)。此外AbT5xrAppleUvW正確地不匹配,因爲它在蘋果之前有AbT5xr而不是AbT5xY
  2. 我認爲C#的RegEx有一些名爲替換,組,捕獲,需要在這裏使用,但我在這裏如何使用這些掙扎。
+0

只做2個正則表達式並替換2次。我不認爲你可以做任何其他的方式 –

+0

只是嘗試使用'替換(字符串輸入,字符串模式,MatchEvaluator評估器)'您的自定義'MatchEvaluator'會給你正確的值,你想要的匹配字符串值 –

+0

@JakubDąbek我剛剛添加了註釋2. – nam

回答

4

您可以捕捉Applemango成1組和更換時,用一根火柴評估,在那裏你可以檢查組1的值,然後根據檢查結果進行必要的更換:

var pat = @"AbT5xY\s*(Apple|mango)"; 
var s = "This AbT5xY\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\nmangoUvW test"; 
var res = Regex.Replace(s, pat, m => 
     m.Groups[1].Value == "Apple" ? "Fruit1" : "Fruit2"); 
Console.WriteLine(res); 
// => This Fruit1UvW is a test Fruit1UvW is a test and AbT5xrAppleUvW and another Fruit2UvW test 

請參閱C# demo

AbT5xY\s*(Apple|mango)正則表達式匹配AbT5xY,然後0+空格(注意單個反斜線作爲我使用的逐字字符串文字),然後相匹配,並捕獲任何Applemango成1組的m.Groups[1].Value == "Apple"如果組1個值是Apple ,然後繼續更換比賽。

+1

從您的解決方案中,我也學會了如何使用LINQ進行匹配評估 - 如果相應的評估過程不太複雜,這很方便。 – nam

+0

@nam我在這裏很挑剔,但是這裏沒有LINQ,只是一個lambda表達式。語義相當混亂,因爲人們幾乎主要在LINQ查詢中看到lambdas。 –

+0

@JakubDąbek同意。 Linq使用Lambda表達式來執行其一些功能 – nam