Escape Search Term - CSharp System

CSharp examples for System:String Escape

Description

Escape Search Term

Demo Code


using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Text;
using System.Linq;
using System.Globalization;
using System.ComponentModel;
using System.Collections.Generic;
using System;/* w ww.  java  2  s  .  c  om*/

public class Main{
        public static string EscapeSearchTerm(this string term)
		{
			char[] specialCharcters = { '+', '-', '!', '(', ')', '{', '}', '[', ']', '^', '"', '~', '*', '?', ':', '\\' };
			var retVal = "";
			//'&&', '||',
			foreach (var ch in term)
			{
				if (specialCharcters.Any(x => x == ch))
				{
					retVal += "\\";
				}
				retVal += ch;
			}
			retVal = retVal.Replace("&&", @"\&&");
			retVal = retVal.Replace("||", @"\||");
			retVal = retVal.Trim();

			return retVal;
		}
}

Related Tutorials