简体   繁体   中英

How to write a Regex pattern for the following string?

I am trying to write a Regex pattern to modify the caption of my datagridview. I need to remove following characters from each string: space [ ] * # ? / \\ @ ( ) . "" '' I am super confused and I need your help in defining the patter of the Regex in C#. This is my sample code:

DataTable d_new = d;
for (int i = 0; i < d.Columns.Count; i++)
{
    string t = d.Columns[i].Caption;
    string regex = "\\s+"; // this needs to Be expanded
    string t_new = Regex.Replace(t, regex, "_");
    d.Columns[i].Caption = t_new;
}
var invalidChars = new HashSet<char>(@"[]*#?/\@()");
var output = new string( input.Where(c => !invalidChars.Contains(c)).ToArray() );

This would match what you want, just replace with an empty string or what you want.

[ \[\]*#?/\\@()."']

But in this case an regex is a bit overkill, you could just use Remove .

这应该可以解决问题:

 string regex = "[\[\]*#?\/\\@()."']";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM