• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 657
  • 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
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

 
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

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