Regex: replacing \n and spaces

T

Trev

Hi everyone,
I'm having some problems using Regex; I have a long string that is
delimetered in a random fashion by a combination of spaces and \n's for
newlines. I have five possiblities:

// Character can be a-zA-Z0-9 plus any non-alphanumeric character (. ,
\ [ ] etc.)
// five possibilities:
// 1: Characters \nCharacters -> Characters Characters
// 2: Characters\n Characters -> Characters Characters
// 3: Characters \nCharacters -> Characters Characters
// 4: Characters \n Characters -> Characters Characters
// 5: Characters\nCharacters -> Characters Characters

So that a string like
A B \nC D\n E\nF \n G\nH
becomes
A B C D E F G H

Would regex be the "right" method to use, or some of the C# String
methods, like replace(...)?
If the former, could someone give me some helpful advice? It looks,
like for case 1, the regex
string would be something like .*\s\n.* but in this case, isn't \n
regarded as whitespace, like \s ?

TIA

Trev
 
D

Davey

Try this:

static string removeSpaceNewLine(string inputString)
{
return Regex.Replace(inputString, @"[\s]{1,}", " ");
}

I've tested with all your samples. Works fine.

string s1 = removeSpaceNewLine("Characters \nCharacters");
string s2 = removeSpaceNewLine("Characters\n Characters");
string s3 = removeSpaceNewLine("Characters \nCharacters");
string s4 = removeSpaceNewLine("Characters \n Characters");
string s5 = removeSpaceNewLine("Characters\nCharacters");
string s6 = removeSpaceNewLine("A B \nC D\n E\nF \n G\nH");

Davey

=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Beer is part of the life.
http://www.lovebeers.com
=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 
O

Oliver Sturm

Hello Davey,

I believe you that your solution works, so I haven't even checked with the
OP :) I just wanted to add that the expression you show

[\s]{1,}

seems rather complicated to me - it should be absolutely equal to

\s+

which is a lot simpler.


Oliver Sturm
 
D

Davey

Thanks Oliver, you are absolutely right. I am new to Regular Express.
It is just so confusing.

Davey.

=-=-=-=-=-=-=-=-=-=-=-=-=-=-
Beer is part of the life.
http://www.lovebeers.com
=-=-=-=-=-=-=-=-=-=-=-=-=-=-
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top