[英]Exact/Literal word or pattern match regex
我正在嘗試將表中的模式與用戶話語相匹配。
string userUtterance = "I want identification number for number of customers";
string pattern1 = "identification number";
string pattern2 = "tom";
string pattern3 = "id";
所需結果:
bool match1 = regex.Ismatch(userUtterance, pattern1); // should match
if(match1 == true)
{
// replace only the matched pattern in userUtterance
};
bool match2 = regex.Ismatch(userUtterance, pattern2); // should not match
bool match3 = regex.Ismatch(userUtterance, pattern3); // should not match
我想對使用符合該語法的正則表達式提供一些建議,以限制歧義匹配並完全匹配字面值。
謝謝
您可以將錨 \\b
用於單詞邊界:
"\bonly these words\b"
這將僅與這些句子中的這些單詞匹配:
這只是這些詞,寶貝。
這是“只有這些話”的寶貝。
寶貝,這只是這些話。
這只是這些話。
我說:“只有這些話”。
代替正則表達式進行替換,您可以嘗試以下操作:
string userUtterance = "I want identification number for number of customers";
string pattern1 = "identification number";
string pattern2 = "\btom \b";
string pattern3 = "\bid \b";
string replacement = "{YourWordHere}"
string newuserUtterance = userUtterance.Replace(pattern1, replacement );
bool match2 = Regex.IsMatch(newuserUtterance, pattern2); // should not match
bool match3 = Regex.IsMatch(newuserUtterance, pattern3); // should not match
這將取代pattern1
中的字符串userUtterance
與replacement
然后測試tom
<=注意空格,是否在新創建的字符串中,然后它將測試id
<=再次注意空格,是否在新字符串中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.