[英]How to check for variable character in string and match it with another string of same length?
我有一個相當復雜的問題,我無法弄清楚。
我每 10 秒從另一個進程中獲取一組字符串,其中第一組的前 5 個字符是常量,接下來的 3 個是可變的並且可以更改。 然后是另一組字符串,其中前 3 個是可變的,接下來的 3 個是常量。
我想將這些值與固定字符串進行比較,以檢查第一組字符串(ABCDE*** == ABCDEFGH)中的前 5 個字符是否匹配,並在確保長度相同的同時忽略最后 3 個變量字符。 例如:如果 (ABCDE*** == ABCDEDEF) 則條件為真,但如果 (ABCDE*** == ABCDDEFG) 則條件為假,因為前 5 個字符不相同,如果 (ABCDE*** = = ABCDEFV) 條件應該為假,因為缺少一個字符。
我在固定字符串中使用 * 來嘗試在比較時使長度相同。
這能解決您的要求嗎?
private static bool MatchesPattern(string input)
{
const string fixedString = "ABCDExyz";
return fixedString.Length == input.Length && fixedString.Substring(0, 5).Equals(input.Substring(0, 5));
}
在 C# 的最新版本中,您還可以使用范圍:
private static bool MatchesPattern(string input)
{
const string fixedString = "ABCDExyz";
return fixedString.Length == input.Length && fixedString[..5].Equals(input[..5]);
}
看到這個小提琴。
順便說一句:您可以使用正則表達式實現相同的效果。
如果您匹配的字符串在編譯時是已知的,那么您最好的選擇可能是使用正則表達式。 在第一種情況下,匹配^ABCDE...$
。 在第二種情況下,匹配^...DEF$
。
另一種方法,如果匹配字符串未知,可能會更好,使用 Length、StartsWith 和 EndsWith:
String prefix = "ABCDE";
if (str.Length == 8 && str.StartsWith(prefix)) {
// do something
}
然后對於第二種情況類似,但使用 EndsWith 而不是 StartsWith。
進行抽象總是一個好主意。 在這里,我制作了一個簡單的函數,它接受模式和值並進行檢查:
bool PatternMatches(string pattern, string value)
{
// The null string doesn't match any pattern
if (value == 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;
}
然后你可以這樣稱呼它:
bool b1 = PatternMatches("ABCDE***", "ABCDEFGH");
bool b2 = PatternMatches("ABC***", "ABCDEF");
您可以使用正則表達式,但這是相當易讀的,RegExes 並不總是如此。
這是 dotnetfiddle 的鏈接: https ://dotnetfiddle.net/4x1U1E
檢查這個
public bool Comparing(string str1, string str2)
=> str2.StartWith(str1.replace("*","")) && str1.length == str2.Length;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.