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;
}
}
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. "
source to share
There are already enough correct answers above. So I'll just add that Mastering Regular Expressions is a great resource for understanding regex better
source to share