Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the regular expression to replace white space with a specified character?

Tags:

c#

regex

I have searched lot of questions and answers but, I just got lengthy and complicated expressions. Now I want to replace all white spaces from the string. I know it can be done by regex. but, I don't have enough knowledge about regex and how to replace all white space with ','(comma) using it. I have checked some links but, I didn't get exact answer. If you have any link of posted question or answer like this. please suggest me.

My string is defined as below.

string sText = "BankMaster      AccountNo              decimal      To   varchar";

and the result should be return as below.

"BankMaster,AccountNo,decimal,To,varchar"

Full Code:

string sItems = Clipboard.GetText();
string[] lines = sItems.Split('\n');
for (int iLine =0; iLine<lines.Length;iLine++)
{
    string sLine = lines[iLine];
    sLine = //CODE TO REPLACE WHITE SPACE WITH ','
    string[] cells = sLine.Split(',');

    grdGrid.Rows.Add(iLine, cells[0], cells[1], cells[2], cells[4]);
}

Additional Details

I have more than 16000 line in a list. and all lines are same formatted like given example above. So, I am going to use regular expression instead of loop and recursive function call. If you have any other way to make this process more faster than regex then please suggest me.

like image 411
Shell Avatar asked Mar 04 '14 07:03

Shell


2 Answers

string result = Regex.Replace(sText, "\\s+", ",");

\s+ stands for "capture all sequential whitespaces of any kind".

By whitespace regex engine undeerstands space (), tab (\t), newline (\n) and caret return (\r)

like image 127
J0HN Avatar answered Nov 14 '22 23:11

J0HN


string a = "Some    text  with   spaces";
Regex rgx = new Regex("\\s+");
string result = rgx.Replace(a, ",");

Console.WriteLine(result);

The code above will replace all the white spaces with ',' character

like image 32
Rami Avatar answered Nov 14 '22 23:11

Rami