简体   繁体   中英

RegEx for comparison of two strings with special characters

I am using .Equals() method to check equality of my strings. I have over a dozen different strings and it is working fine for all the strings but I got stuck with Phone number and Address.

I have stringA as (111)-22-3333 and stringB as 111223333.

Is it possible to make use of regex to make this comparison result in true while still doing .Equals(). I am new to RegEx.

I tried using replaceAll before doing .Equals but I got "String does not contain a definition for replaceAll....." error.

As you have correctly explained you can make use of a combination of RegEx and String comparison (Equals) here. First I would remove every non-numeric character from the stringA (using RegEx) and afterwards compare the two strings. In code it would look like this:

stringA = "(111)-22-3333";
stringB = "11122333";

if(Regex.Replace(stringA, "[^0-9]", "").Equals(stringB)) {
   Console.WriteLine("Match found!");
}else {
   Console.WriteLine("Try again...");
}

This should work fine for your solution, I verified it to work on my local machine. Anyways I'm not sure how this would perform for huge strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM