tags:

views:

182

answers:

5
class Program
    {
        static void Main(string[] args)
        {
            string s = "the U.S.A love UK";
            Console.WriteLine(replace(s));
        }

        public static string replace(string s)
        {
            s = Regex.Replace(s, @"^U.S.A", " United state Of America");
            s = Regex.Replace(s, @"^Uk", "United kingdom");
            return s;
        }

    }

Why its not replacing the U.S.A with " united state of Amiriaca and uk with united kingdom i did it but its not workin

+3  A: 

Well, look at the search pattern in your regex.

The ^ has a specific meaning. (as do the . but they won't actually fail in this case, but they aren't doing what you think they are)

annakata
+1  A: 
  1. The . in your U.S.A expression will match any single character. I doubt that's what you intend.
  2. The ^ pins your expression to the beginning of the string. You don't want it.
  3. By default, regular expressions are case sensitive. If you want Uk to match UK you need to specify a case-insensitive compare.
Joel Coehoorn
+1  A: 

To expand upon annakata's answer:

In regular expressions the '^' character means "match at the beginning of the String", so if you wanted "U.S.A." to be replaced, it would have to be the first six characters in the string, same for UK. Drop the '^' from your RE, and it should work.

And regarding the comment about the '.' character, in regular expressions this means match any character. If you wish to match a literal '.' you must escape it like this "."

foxxtrot
I was kind of deliberately not expanding on the grounds it's a homework question ;)
annakata
That's a fair point, I missed that tag when I was looking at this initially.
foxxtrot
+1  A: 

For simple replacements, you don't need Regular expressions:

string s = "the U.S.A love UK";
s = s.Replace("U.S.A", "United States of America").Replace("UK", "United Kingdom");
CMS
hehe: this is my standard response to most regex questions, but I saw the homework tag and took that to mean that using a regex was part of the assignment.
Joel Coehoorn
A: 

There are already enough correct answers above. So I'll just add that an excellent resource for better understanding regular expressions is Mastering Regular Expressions

Gavin Miller