Regex.Replace

  • Thread starter Thread starter Omega
  • Start date Start date
O

Omega

Hi all

I use Regex.Replace to capitalize files name. Here is the code:

-----------------------------
static string CapitalizeText(string s)
{
return Regex.Replace(s, @"\w+", new
MatchEvaluator(CapitalizeText));
}

static string CapitalizeText(Match m)
{
string x = m.ToString();
if (char.IsLower(x[0]))
{
return char.ToUpper(x[0]) + x.Substring(1, x.Length-1);
}
return x;
}
-------------------------------------

if I call:

CapitalizeText("laura pausini - it's not goodbye.mp3")

I'll get "Laura Pausini - It'S Not Goodbye.Mp3", as you see, the uppercase
of 'S' in 'It's' is not so nice, how can I prevent this (by modify the
expression "\w+") ?

Thankyou
 
Funny, last mesage I wrote I told someone to use Regex. And in this one
I'm telling you NOT to.

Replace both methods with:

static string CapitalizeText(string s)
{
System.Globalization.TextInfo myTI = new
System.Globalization.CultureInfo("en-US",false).TextInfo;
return myTI.ToTitleCase(s);
}

Now CapitalizeText("laura pausini - it's not goodbye.mp3")
returns: Laura Pausini - It's Not Goodbye.Mp3

You may want to move the myTI object to a class-level static.
 
Great !

It works the way I wanted.

Thank you

Funny, last mesage I wrote I told someone to use Regex. And in this one
I'm telling you NOT to.

Replace both methods with:

static string CapitalizeText(string s)
{
System.Globalization.TextInfo myTI = new
System.Globalization.CultureInfo("en-US",false).TextInfo;
return myTI.ToTitleCase(s);
}

Now CapitalizeText("laura pausini - it's not goodbye.mp3")
returns: Laura Pausini - It's Not Goodbye.Mp3

You may want to move the myTI object to a class-level static.



Omega said:
Hi all

I use Regex.Replace to capitalize files name. Here is the code:

-----------------------------
static string CapitalizeText(string s)
{
return Regex.Replace(s, @"\w+", new
MatchEvaluator(CapitalizeText));
}

static string CapitalizeText(Match m)
{
string x = m.ToString();
if (char.IsLower(x[0]))
{
return char.ToUpper(x[0]) + x.Substring(1, x.Length-1);
}
return x;
}
-------------------------------------

if I call:

CapitalizeText("laura pausini - it's not goodbye.mp3")

I'll get "Laura Pausini - It'S Not Goodbye.Mp3", as you see, the uppercase
of 'S' in 'It's' is not so nice, how can I prevent this (by modify the
expression "\w+") ?

Thankyou
 
How about using the System.Globalization.TextInfo class?

using System.Globalization;

static string CapitalizeText(string s)
{
TextInfo ti = new CultureInfo("en-US", false).TextInfo;
return ti.ToTitleCase(s);
}

--
HTH,

Kevin Spencer
Microsoft MVP
..Net Developer
A watched clock never boils.
 

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

Back
Top