1

In the following code I want to replace every occurrence of "U.S.A" with "united states of America" and every occurrence of "uk" with "united kingdom" in a string, but it does not seem to work. How do I fix it?

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;
        }

    }

5 Answers 5

3

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)

Sign up to request clarification or add additional context in comments.

Comments

1

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");

1 Comment

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.
1
  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.

Comments

1

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 "."

2 Comments

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.