Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 648
  • Last Modified:

Help on Creating a C# Regex.Replace expression

Hi all.

I´m trying to use Regex.Replace to replace the last comma on a string to 'and'. By eg:

"Im using laptop A, laptop B, laptop C".

After using Regex.Replace, I want:

"Im using laptop A, laptop B and laptop C".

How could I do this?
0
regisdaniel
Asked:
regisdaniel
1 Solution
 
felipevidaurriCommented:
Try this code:

            string Text1 = "Im using laptop A, laptop B, laptop C";

            MessageBox.Show(Text1.Replace(",", " and"));
0
 
regisdanielAuthor Commented:
Hi felipe.

I don´t wan´t to replace all ocurrences of comma on the string.
Only the LAST one.

"Im using laptop A, laptop B, laptop C".
"Im using laptop A, laptop B and laptop C".
0
 
MikkelAStrojekCommented:
Don't know about regex but you could do the following instead:
string s = "Im using laptop A, laptop B, laptop C.";
            string tr = "Im using laptop A, laptop B and laptop C.";
            int i  =s.LastIndexOf(",");
            s = s.Remove(i,1);
            s = s.Insert(i, " and");
            Console.WriteLine(tr.Equals (s));

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
amitnepalCommented:
string Text1 = "Im using laptop A, laptop B, laptop C";

            MessageBox.Show(Text1.Replace(Text1.indexof(",",1), " and"));
0
 
regisdanielAuthor Commented:
Hello MikkelAStrojek, thanks to your help.

But i really like to use Regex on this solution.
I found a example on the web:

http://stackoverflow.com/questions/3829483/how-to-replace-last-occurrence-of-characters-in-a-string-using-javascript

But I did´t realize a way to implement that on c#.

Thanks!
0
 
MikkelAStrojekCommented:
Ok... The below will do the trick.
string s1 = "Im using laptop A, laptop B, laptop C.";
s1 = System.Text.RegularExpressions.Regex.Replace(s1, @",(?=[^,]*\z)", " and");      

Open in new window

0
 
regisdanielAuthor Commented:
Great! Thanks!!!
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now