user1558211
user1558211

Reputation: 37

Replace all characters not included in characters OR sequences list

i am working on C# code that should replace all unknown (unknown = other that available) characters to one character choosen by me (e.g. '?'). Available characters can be single characters, OR a sequence of two or more characters.

For example:

Input string: AXBY@@CZ
Available characters or sequences: A, B, C, @@
Desired output: A?B?@@C?

Other example:

Input string: AXBY@CZ
Available characters or sequences: A, B, C, @@
Desired output: A?B??C?

I want to achieve this using a regex expression. The closest i got to the solution is a regex like this:

(?!@@|[ABC]).

But in an example of input string like this it will result in a wrong result:

Input string: AXBY@@CZ
Result from above regex: A?B?@?C?
Instead of wanted by me: A?B?@@C?

How i can achieve my goal?

Upvotes: 2

Views: 129

Answers (1)

Sebastian Schumann
Sebastian Schumann

Reputation: 3446

A sample to the hint of Wiktor Stribiżew:

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

DEMO

Returns A?B?@@?C?A for input AXBY@@CZ@A.

Keep in mind the hint of Dmitry Bychenko. This sample doesn't answer his question.

Upvotes: 3

Related Questions