Need help with regex

A

Andi Reisenhofer

Hallo folks,

Just started to use regex a bit with c#.
Want to do the following perhaps somebody have a tip.

1) want to remove trailing and leading whitespaces from the string.
Tried this one here:
string delim = " \t\r\n";
to = from.Trim (delim.ToCharArray ());

2) remove all \t and \r from the string and replace them through blanks
?.
3) remove all spaces which are more than one.
(only one blank should be between each words)
(1 2 3 4 5 -> 1 2 3 4 5)
Tried this one here:
to = Regex.Replace (from, "[ ]{2,}", "", RegexOptions.None);

Thanks
Reg. Andreas
 
J

Jon Skeet [C# MVP]

Andi Reisenhofer said:
Hallo folks,

Just started to use regex a bit with c#.

I don't think that your first two examples need regular expressions at
all...
Want to do the following perhaps somebody have a tip.

1) want to remove trailing and leading whitespaces from the string.
Tried this one here:
string delim = " \t\r\n";
to = from.Trim (delim.ToCharArray ());

That should work fine - could you give an example of it not working?
2) remove all \t and \r from the string and replace them through blanks
?.

to = from.Replace ('\t', ' ').Replace ('\r', ' ');
3) remove all spaces which are more than one.
(only one blank should be between each words)
(1 2 3 4 5 -> 1 2 3 4 5)
Tried this one here:
to = Regex.Replace (from, "[ ]{2,}", "", RegexOptions.None);

I think you mean

to = Regex.Replace (from, "[ ]{2,}", " ", RegexOptions.None);

That seems to work for me.
 

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

Similar Threads

Regex Usage, or use Substring? 3
regex challenge 9
question on regex for splitting a csv file 2
RegEx problem 7
Need help in RegEx 2
regex groups 2
Need help with Regex 1
How to get rid of the regex???? 6

Top