Skip to main content
 首页 » 编程设计

c#之精确/文字单词或模式匹配正则表达式

2024年02月13日31zhoujg

我正在尝试将表中的模式与用户话语 匹配。

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 

我想就使用匹配该语法的正则表达式来限制歧义匹配和精确匹配字面词提出一些建议。

谢谢

请您参考如下方法:

您可以使用 anchor \b 作为单词边界:

"\bonly these words\b" 

这将匹配这些句子中的仅这些词:

Here are only these words baby.

Here are "only these words" baby.

Here are only these words, baby.

Here are only these words.

I said: 'only these words'.