【问题标题】:How to find a string with missing fragments?如何找到缺少片段的字符串?
【发布时间】:2013-12-23 16:10:45
【问题描述】:

我正在使用AIML filesC# 中构建一个聊天机器人,目前我有这段代码要处理:

<aiml>
    <category>
        <pattern>a * is a *</pattern>
        <template>when a <star index="1"/> is not a <star index="2"/>?</template>
    </category>
</aiml>

我想做这样的事情:

if (user_string == pattern_string) return template_string;

但我不知道如何告诉计算机star 字符可以是任何东西,特别是可以不止一个字! 我想用正则表达式来做,但我没有足够的经验。有人可以帮助我吗? :)

【问题讨论】:

标签: c# regex aiml


【解决方案1】:

使用正则表达式

static bool TryParse(string pattern, string text, out string[] wildcardValues)
{
    // ^ and $ means that whole string must be matched
    // Regex.Escape (http://msdn.microsoft.com/en-us/library/system.text.regularexpressions.regex.escape(v=vs.110).aspx)
    // (.+) means capture at least one character and place it in match.Groups
    var regexPattern = string.Format("^{0}$", Regex.Escape(pattern).Replace(@"\*", "(.+)"));

    var match = Regex.Match(text, regexPattern, RegexOptions.Singleline);
    if (!match.Success)
    {
        wildcardValues = null;
        return false;
    }

    //skip the first one since it is the whole text
    wildcardValues = match.Groups.Cast<Group>().Skip(1).Select(i => i.Value).ToArray();
    return true;
}

示例用法

string[] wildcardValues;
if(TryParse("Hello *. * * to *", "Hello World. Happy holidays to all", out wildcardValues))
{
    //it's a match
    //wildcardValues contains the values of the wildcard which is
    //['World','Happy','holidays','all'] in this sample
}

顺便说一句,您实际上并不需要正则表达式,这太过分了。只需通过使用 string.Split 将模式拆分为标记然后使用 string.IndexOf 查找每个标记来实现您自己的算法。虽然使用 Regex 确实会缩短代码

【讨论】:

  • RegEx 可能有点矫枉过正,但除非存在巨大的性能问题,否则我认为没有任何理由实施自定义算法。
【解决方案2】:

你认为这对你有用吗?

Match match = Regex.Match(pattern_string, @"<pattern>a [^<]+ is a [^<]+</pattern>");
if (match.Success)
{
    // do something...
}

这里[^代表一个或多个字符是/不是

如果您认为您的 * 中可能有 .+ 而不是 [^
但这会有风险,因为 .+ 表示任何字符都有一次或多次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-20
    • 1970-01-01
    • 1970-01-01
    • 2021-10-16
    • 2015-03-15
    • 1970-01-01
    • 2021-05-03
    • 1970-01-01
    相关资源
    最近更新 更多