现在的位置: 首页 > 综合 > 正文

正则表达式用于字符串提取

2017年10月21日 ⁄ 综合 ⁄ 共 1479字 ⁄ 字号 评论关闭

需要从文本中抽取字符串,例如,从下面的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用()来确定。



抱歉!评论已关闭.