2013-12-23 35 views
4

我使用AIML files建設C#一個聊天機器人,此刻我有這個代碼的過程:如何查找缺少碎片的字符串?

<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角色可以是任何東西,特別是可以不止一個詞! 我想用正則表達式來做,但我沒有足夠的經驗。有人能幫助我嗎? :)

+0

這可能有所幫助:http://stackoverflow.com/a/15275806/607162 – Johnny5

回答

0

你認爲這應該適合你嗎?

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

這裏[^ <] +代表一個或多個字符,這是/不是<

如果你認爲你可能在你的* <的性格,那麼你可以簡單地使用。的+代替[^ <] +
但是,這將是有風險的作爲。+指任何茶有一次或多次的賽事。

2

使用正則表達式

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找到每個令牌。雖然使用正則表達式確實導致代碼更短

+1

正則表達式可能會矯枉過正,但除非存在巨大的性能問題,否則我沒有看到任何理由實現自定義算法。 – Johnny5