需要从文本中抽取字符串,例如,从下面的xml文本中抽取link和title的值,
<RssFeeds>
<link>http://www.codeguru.com/icom_includes/feeds/codeguru/rss-all.xml</link>
<title>CodeGuru.com</title>
<description>something</description>
</RssFeeds>
<RssFeeds>
<link>http://lifehacker.com/index.xml</link>
<title>Lifehacker</title>
<description>something</description>
</RssFeeds>
可以用如下的C#代码实现:
private void buttonRegular_Click(object sender, EventArgs e) { String myString = @"<RssFeeds> <link>http://www.codeguru.com/icom_includes/feeds/codeguru/rss-all.xml</link> <title>CodeGuru.com</title> <description>something</description> </RssFeeds> <RssFeeds> <link>http://lifehacker.com/index.xml</link> <title>Lifehacker</title> <description>something</description> </RssFeeds> "; Regex linkRegex = new Regex(@"<link>\s*(?<link>[^<]+)\s*</link>", System.Text.RegularExpressions.RegexOptions.Compiled); Regex titleRegex = new Regex(@"<title>\s*(?<title>[^<]+)\s*</title>", System.Text.RegularExpressions.RegexOptions.Compiled); Match mLink = linkRegex.Match(myString); while (mLink.Success) { string link = mLink.Groups["link"].Value; MessageBox.Show(link); mLink = mLink.NextMatch(); } Match mTitle = titleRegex.Match(myString); while (mTitle.Success) { string title = mTitle.Groups["title"].Value; MessageBox.Show(title); mTitle = mTitle.NextMatch(); } }
可以遍历整个文本,直到提取完所有需要的内容,这里要注意Match类有Groups的概念,有了这个概念可以抽取正则表达式中定义的一个group,group用()来确定。