2016-09-19 18 views
2

我正在處理將所有未知(未知=其他可用)字符替換爲由我選擇的一個字符(例如'?')的C#代碼。可用字符可以是單個字符,或兩個或多個字符的序列替換字符中未包含的所有字符或序列列表

例如:

Input string: [email protected]@CZ 
Available characters or sequences: A, B, C, @@ 
Desired output: [email protected]@C? 

其他例如:

Input string: [email protected] 
Available characters or sequences: A, B, C, @@ 
Desired output: A?B??C? 

我想要實現這個使用正則表達式表達。我到了解決方案最接近的是這樣的正則表達式:

([email protected]@|[ABC]). 

但在這樣將導致錯誤的結果輸入字符串的例子:

Input string: [email protected]@CZ 
Result from above regex: [email protected]?C? 
Instead of wanted by me: [email protected]@C? 

如何,我可以實現我的目標?

+3

匹配它們並加入匹配值。 –

+0

你能爲我的例子發佈一個正則表達式嗎? – user1558211

+0

問題是,你只消耗一個字符與你的否定前瞻斷言。第一個@匹配,但第二個將被刪除。你可以用這個正則表達式來實現:['(?<!@)@(?!@)| [^ ABC @]'](http://regexstorm.net/tester?p=(%3f%3c!% 40)%40(%3f!%40)%7c%5b%5eABC%40%5d&i = AXBY%40%40CZ&r =%3f)但使用WiktorStribiżew的提示要簡單得多。 –

回答

3

樣本Wiktor的Stribiżew的提示:

var str = "[email protected]@[email protected]"; 
var matches = Regex.Matches(str, "@@|[ABC]").Cast<Match>(); 
var replaced = string.Join("?", matches.Select(x => x.Value)); 
Console.WriteLine(replaced); 

DEMO

返回[email protected]@?C?A FO r輸入[email protected]@[email protected]

請記住德米特里Bychenko的暗示。這個樣本不回答他的問題。

+0

是的,我會這樣做。這可以根據要求進一步增強。 –

-1

這裏是你開始使用什麼Regex

string input = "[email protected]@CZ"; 
string output = Regex.Replace(input, "[^[email protected]]+", "?"); 
Console.WriteLine("Result: {0}", output); 
//Result: [email protected]@C? 

記住添加using System.Text.RegularExpressions;

+0

這不是OP正在尋找的東西。一個'@'應該被替換。只有雙「@」不應該。 –

+0

你是對的,我的壞。 – DarKalimHero

相關問題