輸入:This AbT5xY\nAppleUvW is a test AbT5xY AppleUvW is a test and AbT5xrAppleUvW and another AbT5xY\nmangoUvW test
C#正則表達式 - 匹配特定的字符串後面是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
和芒果之間
- 我忽略空格字符(換行,空格,製表符等)。此外
AbT5xrAppleUvW
正確地不匹配,因爲它在蘋果之前有AbT5xr
而不是AbT5xY
。 - 我認爲C#的RegEx有一些名爲替換,組,捕獲,需要在這裏使用,但我在這裏如何使用這些掙扎。
只做2個正則表達式並替換2次。我不認爲你可以做任何其他的方式 –
只是嘗試使用'替換(字符串輸入,字符串模式,MatchEvaluator評估器)'您的自定義'MatchEvaluator'會給你正確的值,你想要的匹配字符串值 –
@JakubDąbek我剛剛添加了註釋2. – nam