Skip to main content
 首页 » 编程设计

c#之在字符串中查找字符串的出现

2024年02月23日24hnrainll

在另一个字符串中查找一个字符串的最快和最有效的方法是什么。

比如我有这段文字;

"Hey @ronald and @tom where are we going this weekend"

但是我想找到以“@”开头的字符串。

请您参考如下方法:

您可以使用正则表达式。

string test = "Hey @ronald and @tom where are we going this weekend"; 
 
Regex regex = new Regex(@"@[\S]+"); 
MatchCollection matches = regex.Matches(test); 
 
foreach (Match match in matches) 
{ 
    Console.WriteLine(match.Value); 
} 

这将输出:

@ronald 
@tom