Reputation: 1437
I have actually misunderstood the issue originally,
Basically I have checks to see if there is an error, and to check for certain horrible characters that will break it, however this will not work with brackets, i need to basically check if there are ANY brackets within the string before passing it through SQL and if there are, remove them outright from the string.
for example say I have a string that looks like
[I am a magical string with super powers!){
I wish to remove all of these horrible brackets!
if (compiler.Parser.GetErrors().Count == 0)
{
AstNode root = compiler.Parse(phrase.ToLower());
if (compiler.Parser.GetErrors().Count == 0)
{
try
{
fTextSearch = SearchGrammar.ConvertQuery(root, SearchGrammar.TermType.Inflectional);
}
catch
{
fTextSearch = phrase;
}
}
else
{
fTextSearch = phrase;
}
}
else
{
fTextSearch = phrase;
}
string[] errorChars = errorChars = new string[]
{
"'",
"&"
};
StringBuilder sb = new StringBuilder();
string[] splitString = fTextSearch.Split(errorChars, StringSplitOptions.None);
int numNewCharactersAdded = 0;
foreach (string itm in splitString)
{
sb.Append(itm); //append string
if (fTextSearch.Length > (sb.Length - numNewCharactersAdded))
{
sb.Append(fTextSearch[sb.Length - numNewCharactersAdded]); //append splitting character
sb.Append(fTextSearch[sb.Length - numNewCharactersAdded - 1]); //append it again
numNewCharactersAdded++;
}
}
string newString = sb.ToString();
//Union with the full text search
if (!string.IsNullOrEmpty(fTextSearch))
{
sql.AppendLine("UNION");
sql.AppendLine(commonClause);
sql.AppendLine(string.Format("AND CONTAINS(nt.text, '{0}', LANGUAGE 'English')", newString));
}
Upvotes: 0
Views: 1328
Reputation: 2229
this is one way to do it. You can make it more sophisticated by having a set of characters passed in and then testing for those characters rather than hard coding for the brackets.
var someString = "[Hello"
if(someString.contains("["))
{
someString.Replace("[","");
}
if (someString.Contains("]"))
{
someString.Replace("]","");
}
Upvotes: 1
Reputation: 8192
If I understand you right, you just want to remove the brackets if they are not matching.
This will accomplish that:
public string MatchPair(string input, string item1, string item2)
{
var ix1 = input.IndexOf(item1);
var ix2 = input.IndexOf(item2);
if ((ix1 != -1) && (ix2 != -1))
{
return input;
}
if (ix1 == -1)
{
return this.CutString(input, ix2, item2);
}
if (ix2 == -1)
{
return this.CutString(input, ix1, item1);
}
return string.Empty;
}
public string CutString(string input, int ix, string item)
{
string left = input.Substring(0, ix);
string right = input.Substring(ix + item.Length);
return left + right;
}
Here is some testdata that I used:
var str1 = "[hello]";
var str2 = "[hello";
var str3 = "hel]lo";
var str4 = "hel[lo";
var res1 = this.MatchPair(str1, "[", "]");
var res2 = this.MatchPair(str2, "[", "]");
var res3 = this.MatchPair(str3, "[", "]");
var res4 = this.MatchPair(str4, "[", "]");
Upvotes: 0