【问题标题】:Pattern to List of Patterns模式到模式列表
【发布时间】:2018-05-23 00:30:44
【问题描述】:

我实际上有这种情况,我必须验证是否存在重叠模式(可能是正则表达式或其他)。

string pattern = "123*"
string[] patterns = new string[]  { "123?", "123*", "12?", "*23*" }

我相信从这里重叠的匹配是"123?""123*""*23*"

对于任何尾随字符,通配符将被限制为 "*" 和/或对于任何 1 长度的 "?"

顺便说一句,这是出于数字格式的目的,因此也有可能在数字模式/格式中包含文字破折号(最多)。

这可以用正则表达式或其他方法完成吗?如果可能的话,在 C# / Javascript 中。

请对我错过的任何信息发表评论。

TIA

【问题讨论】:

  • 您好,我无法获得您想要实现的目标。请详细说明。
  • 我认为您需要指定要涵盖多少语法;如果我们限制在?*. 是可行的,但如果你进入复杂的前瞻和捕获组等,这将很难甚至不可能。
  • @KenY-N 嗨,肯尼,我认为我仅限于数字,例如 8 位数字或带有破折号的数字格式,所以是的,对于通配符和我安静地限制的东西星号和问号表示长度
  • ?12? 中是什么意思?
  • @revo 我刚刚进行了编辑,希望它能进一步解决问题

标签: javascript c# regex pattern-matching


【解决方案1】:

只是想分享我目前的解决方案,但这是通过 C# 实现的。

static string regRep(string inp)
{
    return inp.Replace("*", ".*").Replace('?', '.').Replace("-", @"\-");
}

static string regRep2(string inp)
{
    return inp.Replace("*", ".*").Replace('?', '.').Replace("-", ".");
}

static void Main()
{
    var patterns = new string[] { "8888*", "8889*", "8898*", "8899*", "8988*", "8989*", "8989*", "8999*", "7898*", "7899*", "8888?8", "888?-8", "*88*" };
    string ar = @"888?-*";

    List<string> res = new List<string>();

    bool mat1, mat2;
    Regex reg1, reg2;
    foreach (var reg in patterns)
    {
        reg1 = new Regex(regRep(reg));
        reg2 = new Regex(regRep(ar));

        mat1 = reg1.IsMatch(ar);
        mat2 = reg2.IsMatch(reg);

        // standard matching
        if (mat1 || mat2)
        {
            res.Add($"{ar} std matched with {reg}");
        }
        else
        {
            //forced matching
            reg1 = new Regex(regRep2(reg));
            reg2 = new Regex(regRep2(ar));
            mat1 = reg1.IsMatch(ar);
            mat2 = reg2.IsMatch(reg);

            if (mat1 || mat2)
            {
                res.Add($"{ar} frc matched with {reg}");
            }
        }
    }
}
//result
Count = 5
    [0]: "888?-* frc matched with 8888*"
    [1]: "888?-* frc matched with 8889*"
    [2]: "888?-* frc matched with 8888?8"
    [3]: "888?-* std matched with 888?-8"
    [4]: "888?-* std matched with *88*"

这个现在对我有用,我希望有人也会,如果没有,更好。谢谢!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2019-07-17
    • 1970-01-01
    • 2019-12-28
    • 2017-11-26
    • 2011-05-11
    • 2015-04-29
    相关资源
    最近更新 更多