需要比较具有一个或多个动态单词的字符串

本文关键字:动态 单词 字符串 比较 具有一 有一个 | 更新日期: 2023-09-27 18:17:22

我是c#(Pattern)验证字符串。

验证的问题是,它包含一个或多个单词动态

例如:

第一个字符串- 新的票证更新- ID:新的优先级:新的在GSD中分配给您一个新的票证/操作项。

第二串-#票务更新- ID:#优先级:#在GSD中分配给您一个新的票务/操作项。

我在我的DB中有第二个字符串,我已经用#替换了动态单词,它可以是任何东西。

第一个字符串来验证它是否与第二个字符串中给出的模式匹配。

我知道它可以使用字符串拆分操作来完成,但是我们是否有任何替代方法来提高效率,因为拆分操作很繁重,比如我们可以用正则表达式或其他东西来做吗?

如果第一个字符串是:AnyWordWithNumbers票务更新ID:AnyWordWithNumbers优先级:AnyWordWithNumbers一个新的票务/行动项目被分配给你在GSD

所以这个字符串是有效的。如果第一个字符串是:AnyWordWithNumbers Tt更新ID:AnyWordWithNumbers优先级:AnyWordWithNumbers一个新的票证/行动项目被分配给你在GSD

缺少最后一个(.),并且票的拼写错误,则无效。

Not:可以是任何

需要比较具有一个或多个动态单词的字符串

你可以使用这个正则表达式:

private static readonly Regex TestRegex = new Regex(@"^([A-Za-z0-9]+) Ticket Update- ID:'1 with Priority:'1 A New ticket/action item is assigned to you in GSD'.$");
public bool IsValid(string testString)
{ 
   return (TestRegex.IsMatch(testString));
}

在正则表达式中,'w代表字母、下划线和数字。所以你可以使用

进行测试
If (Regex.IsMatch(input, @"^'w+ Ticket Update- ID:'w+ with Priority:'w+ A New ticket/action item is assigned to you in GSD'.$") {
}

如果它必须是相同的单词三次,你可以使用之前匹配的组'n:

If (Regex.IsMatch(input, @"^('w+) Ticket Update- ID:'1 with Priority:'1 A New ticket/action item is assigned to you in GSD'.$") {
}

如果您希望允许不同的空格,您可以使用's*代表任意数量的空格或's+代表至少一个空格:

If (Regex.IsMatch(input, @"^'s*'w+'s+Ticket Update- ID's*:'s*'w+'s+with Priority's*:'s*'w+'s+A New ticket/action item is assigned to you in GSD'.$") {
}

下面的方法将给出预期的结果。

static bool IsMatch(string templateString, string input)
{
    string[] splittedStr = templateString.Split('#');
    string regExString = splittedStr[0];
    for (int i = 1; i < splittedStr.Length; i++)
    {
        regExString += "[''w''s]*" + splittedStr[i];
    }
    Regex regEx = new Regex(regExString);
    return regEx.IsMatch(input);
}

按如下方式使用上述方法,

string templateString = "# Ticket Update- ID:# with Priority:# A New ticket/action item is assigned to you in GSD";
string testString = "New Ticket Update- ID:New with Priority:New A New ticket/action item is assigned to you in GSD";
bool test = IsMatch(templateString, testString);