Custom trim function - Regex

D

Dan Shanyfelt MCAD

I am new to regex, but I am assuming it provides a better way to do
what I need.

I want to write a custom trim functions that will remove all
occurrences of a non-whitespace character from the beginning or end of
a functions

TrimEnd(string Original, string Pad)
TrimStart(string Original, string Pad)
-Where Pad is a string with a length of 1.

So, TrimEnd("12345XXX", "X") would give "12345".

I know I can do this in a less elegant (and slower) way without Regex,
but this operation will happen frequently.

I am starting to learn Regex, but could use the help to get this
implementation detail knocked out.

TIA,
Dan
 
G

Guest

I am new to regex, but I am assuming it provides a better way to do
what I need.

I want to write a custom trim functions that will remove all
occurrences of a non-whitespace character from the beginning or end of
a functions
Do you know that for regex non-whitespace mean also letters and numbers ?
You are probably looking for:

^(\W)+ - this will find anything like #$%^@@#( also spaces )

and if want start from the back :
$(\W)+

I believe that this site will be extremly helpful :
http://www.roblocher.com/technotes/regexp.aspx

You can test what it wrote above on your sample string to see if it's what
you was looking for.
Jarod
 
D

Daniel Shanyfelt

Thanks Jarod.

That wasn't exactly what I was looking for, but it put me on the right
track.

so..

private string CustomTrimEnd(
string Original,
string TrimChar)
{
Regex r = new Regex(
string.Format("[{0}]+$", TrimChar),
RegexOptions.IgnoreCase);
return r.Split(Original)[0];
}

private string CustomTrimStart(
string Original,
string TrimChar)
{
Regex r = new Regex(
string.Format("^[{0}]+", TrimChar),
RegexOptions.IgnoreCase);
return r.Split(Original)[1];
}

//code from a quick test app

When I move this into the app the same trim char will be used many
times. So, I won't be recreating the pattern every time (just on init).

Again, thanks for the help.

-Dan
 

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


Top