Monday, November 18, 2013

How to use regular expression to trim leading and trailing characters of a specific character in C#

After i enabled filter on the Telerik Grid, the grid filter was not function property, when i copied and paste those search criteria into the filter textbox.

the root cause of this issue is that when i highlight and copy the context in the grid. the context was copied with space in the front and end.  I must trim those leading and trailing space

the following is the filter syntax that i grab via the visual studio debugger

MyColumnName.Contains("  MySearchCriteria  ")

so I need to clear the space before and after double quotation mark.

the regular expression is the good fit for this issue.

first i will define the regular expression pattern to represent the issue.

s*: space appears 0 or more in the string.
\s*\""\*: space before and after the double quotation mark.

var slashRegex = new Regex(@"(?:\s*\""\s*)+");
 
var filterExpression=MyColumnName.Contains("  MySearchCriteria  "); 
  
filterExpression = slashRegex.Replace(filterExpression, "\"");
 

after i apply the regular expression. 


MyColumnName.Contains("MySearchCriteria")