Вопрос

So, let's suppose I have an array of special characters, for example, ".[]{}()\/*+?|^$"

What I want to do is take an input string, for example, ".com", and replace all occurences of special characters with the same character but with a "\" preppended to it.

So for example, the result for that input would be "\.com"

My approach was to iterate over the array of special characters, and search in the input string for the occurence of the current special character, and do the replacement.

The problem is that a "." would be found and replaced with "\.", but then "\" is a special character itself, so it would later be found and be replaced to "\\.".

How can I avoid this and still keep "\" as an special character? (I want "\" to be replaced with "\\", but not in these situations).

I hope I made myself clear enough.

Thank you all for your reading!

Это было полезно?

Решение

Looking at these special characters ".[]{}()\/*+?|^$" as they are regex charactes, I believe you are looking for Regex.Escape method.

Другие советы

If I understand your question, the simple solution seems to be just having '\' be the first element in your array of special characters - then, you replace the '\' characters in the string with '\', '.' with '.' etc, but you don't re-replace the generated '\'s.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top