以下是一个使用正则表达式来捕获字符串并将其作为List
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
public class Program
{
public static void Main(string[] args)
{
string input = "This is a sample string containing multiple words.";
List words = GetWords(input);
Console.WriteLine(string.Join(", ", words));
}
public static List GetWords(string input)
{
List words = new List();
string pattern = @"\b\w+\b"; // 匹配单词的正则表达式
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches)
{
words.Add(match.Value);
}
return words;
}
}
上述代码中的GetWords
方法使用正则表达式\b\w+\b
来匹配输入字符串中的单词。然后,它使用MatchCollection
来存储匹配结果,并将每个匹配的单词添加到List
中。最后,它返回包含所有匹配单词的列表。
在Main
方法中,我们调用GetWords
方法,并使用string.Join
将列表中的单词连接为一个字符串,并将其打印到控制台上。
运行上述代码将输出:This, is, a, sample, string, containing, multiple, words
,这是输入字符串中的所有单词。
下一篇:捕获字符串文本后的所有匹配模式