Skip to main content
 首页 » 编程设计

c#之正则表达式问题匹配前后搜索词

2024年05月10日39dudu

我有这样一句话:

string wordtoFind = "try"; 
string test = "this try that, but it can have multiple try in that"; 

我已经尝试过在类似问题上找到的 2 个正则表达式,但我在使用它们时遇到了问题。正则表达式应该让我找到我需要找到的词(在这种情况下尝试,但它可以是其他词)并在他之前和之后得到这个词(如果没有像在句子开头或在结束)。

尝试 1:

var matches = Regex.Matches(test, @"(?:\\S+\\s)?\\S*"+wordtoFind+"\\S*(?:\\s\\S+)?", RegexOptions.IgnoreCase); 

但匹配返回空

尝试 2:

string pattern = @"(?<before>\w+)" + wordtoFind + "(?<after>\\w+)"; 
MatchCollection matches = Regex.Matches(test, pattern); 
 
for (int z = 0; z < matches.Count; z++) 
{ 
     string error = matches[i].Groups["before"].ToString() + "-" + RetourLabelSansDot + "-" + matches[i].Groups["after"].ToString(); 
} 

也返回空值,我不得不将一些 \ 加倍,因为它会抛出一个错误。对我来说,RegEx 就像魔法一样,我真的不知道如何自定义它们。我的正则表达式有问题还是我使用不当?

这是在 C# 中,

请您参考如下方法:

您的第二个正则表达式是正确的,它返回空,因为您在 try 前后不存在任何单词 char。