Need help with regex

  • Thread starter Thread starter Andi Reisenhofer
  • Start date Start date
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
 
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.
 
Back
Top