Home > Enterprise >  How to check for variable character in string and match it with another string of same length?
How to check for variable character in string and match it with another string of same length?

Time:07-05

I have a rather complex issue that I'am unable to figure out.

I'm getting a set of string every 10 seconds from another process in which the first set has first 5 characters constant, next 3 are variable and can change. And then another set of string in which first 3 are variable and next 3 are constant.

I want to compare these values to a fixed string to check if the first 5 char matches in 1st set of string (ABCDE*** == ABCDEFGH) and ignore the last 3 variable characters while making sure the length is the same. Eg : if (ABCDE*** == ABCDEDEF) then condition is true, but if (ABCDE*** == ABCDDEFG) then the condition is false because the first 5 char is not same, also if (ABCDE*** == ABCDEFV) the condition should be false as one char is missing.

I'm using the * in fixed string to try to make the length same while comparing.

CodePudding user response:

Does this solve your requirements?

private static bool MatchesPattern(string input)
{
    const string fixedString = "ABCDExyz";
    return fixedString.Length == input.Length && fixedString.Substring(0, 5).Equals(input.Substring(0, 5));
}

See this fiddle.

BTW: You could probably achieve the same using regex.

CodePudding user response:

If the string you match against is known at compile time, your best bet is probably using regular expressions. In the first case, match against ^ABCDE...$. In the second case, match against ^...DEF$.

Another way, probably better if the match string is unknown, uses Length, StartsWith and EndsWith:

String prefix = "ABCDE";
if (str.Length == 8 && str.StartsWith(prefix)) {
    // do something
}

Then similarly for the second case, but using EndsWith instead of StartsWith.

CodePudding user response:

It's always a good idea to make an abstraction. Here I've made a simple function that takes the pattern and the value and makes a check:

bool PatternMatches(string pattern, string value)
{
    // The null string doesn't match any pattern
    if (value is null)
    {
        return false;
    }
    // If the value has a different length than the pattern, it doesn't match.
    if (pattern.Length != value.Length)
    {
        return false;
    }
    // If both strings are zero-length, it's considered a match
    bool result = true;
    // Check every character against the pattern
    for (int i = 0; i< pattern.Length; i  )
    { 
        // Logical and the result, * matches everything
        result&= (pattern[i]== '*') ? true: value[i] == pattern[i];
    }
    return result;
}

You can then call it like this:

bool b1 = PatternMatches("ABCDE***", "ABCDEFGH");
bool b2 = PatternMatches("ABC***", "ABCDEF");

You could use regular expressions, but this is fairly readable, RegExes aren't always.

  •  Tags:  
  • c#
  • Related