I tried to replace elements in a string using .NET regex – with no luck 🙂
Assume the following string:
AA A C D A Some Text here
The rules
- Do not replace at beginning of line
- Do only replace single occurrences
- Do not replace if a space is before or after it (optional)
The desired result from above is (# as replacement character):
AA#A C#D A#Some Text here
This should cover all 3 of your requirements. Excuse the formatting; I had to back-tick the first few lines for the
to show up properly.string pattern = @"(?<!^| )((?<!\s) (?!\s))(?!\1)";string[] inputs = { " AA A C D A Some Text here", // original" AA A C D A Some Text here" // space before/after};Output:
Original: AA A C D A Some Text hereResult: AA#A C#D A#Some Text hereOriginal: AA A C D A Some Text hereResult: AA#A C#D A Some Text here