Why isn't the regex replacement method working?

In the following code, I want to replace every occurrence "U.S.A"

with "united states of America"

and every occurrence "uk"

with with "united kingdom"

in a string, but it doesn't seem to work. How to 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;
        }

    }

      

+1


source to share


5 answers


For simple substitutions, 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


source


Ok, take a look at the search pattern in your regex.



^

has a certain meaning. (like .

, but in this case they won't work in this case, but they don't do what you think)

+3


source


  • .

    in your expression U.S.A

    will match any single character. I doubt you intend.
  • ^

    binds your expression to the beginning of the line. You don't want this.
  • By default, regular expressions are case sensitive. If you want to Uk

    match Uk

    then you need to specify case insensitivity.
+1


source


To expand on annakata's answer:

In regular expressions, the "^" character means "match at the beginning of the line", so if you want "USA" to replace it, it must be the first six characters in the line, same for UK. Drop the '^' from your RE and it should work.

And with regard to the comment about '.' character, in regular expressions this means matches any character. If you want to match literal '.' you have to escape from him like that. "

+1


source


There are already enough correct answers above. So I'll just add that Mastering Regular Expressions is a great resource for understanding regex better

0


source







All Articles