Pchp.Library.PCRE.preg_quote C# (CSharp) Method

preg_quote() public static method

Quote regular expression characters.
The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : - Note that / is not a special regular expression character.
public static preg_quote ( string str, string delimiter = null ) : string
str string The string to be escaped.
delimiter string If the optional delimiter is specified, it will also be escaped. /// This is useful for escaping the delimiter that is required by the PCRE functions. The / is the most commonly used delimiter.
return string
        public static string preg_quote(string str, string delimiter = null)
        {
            if (string.IsNullOrEmpty(str))
            {
                return str;
            }

            char delimiterChar = string.IsNullOrEmpty(delimiter)
                ? char.MaxValue // unused (?)
                : delimiter[0];

            StringBuilder result = null;
            int lastEscape = 0;

            for (int i = 0; i < str.Length; i++)
            {
                char ch = str[i];
                bool escape = ch == delimiterChar || PerlRegex.RegexParser.IsDelimiterChar(ch);

                if (escape)
                {
                    if (result == null)
                    {
                        result = new StringBuilder(str.Length + 4);
                    }

                    result.Append(str, lastEscape, i - lastEscape);
                    result.Append('\\');
                    lastEscape = i;
                }
            }

            if (result != null)
            {
                result.Append(str, lastEscape, str.Length - lastEscape);
                return result.ToString();
            }
            else
            {
                return str;
            }
        }