Home > Software engineering >  How to compare string which has dynamic value
How to compare string which has dynamic value

Time:07-14

I have this string. string str = "Connecting to remote server 104.255.152.68 failed"

I want to compare this whole string ignoring "104.255.152.68", something like this - "Connecting to remote server {} failed". if this satisfied will return true.

how to do it ?

CodePudding user response:

You may use Regex.IsMatch to find whether a given string contains this string. Feel free to alter the regular expression as you wish!

Ex:

string str = "Connecting to remote server 104.255.152.68 failed";
string pattern = @"^(Connecting to remote server ).*( failed)$"; 
// This is a regex that will match exactly that string. Instead of .* you may also use [0-9\.]  
// If you remove ^ and $ symbol, then the error string can be searched in a subpart. Including those makes the string exactly equal.
bool errorFound = Regex.IsMatch(str, pattern);

Reference for IsMatch.

CodePudding user response:

  1. Create another string that holds a substring of "Connecting to remote server 104.255.152.68 failed"

In this case, the substring would go from index 0 to 27.

  1. Create a new string that holds the substring you created " {} failed".

Now you have a string that would look like "Connecting to remote server {} failed"

  • Related