.Net Regular Expression在方括号标签之间获取文本

时间:2010-05-12 19:30:56

标签: regex vb.net

好吧,我想抓住

之间的网站上的信息

[usernames]和[/ usernames]

我知道如何获取字符串,但我如何使用正则表达式仅将信息放在中间。

请记住,我将在页面上有更多的东西。

2 个答案:

答案 0 :(得分:3)

    'Sample input
    Dim html = "<html><head><title>Test</title></head>" & vbNewLine & "<body><p>[usernames]Your Name Here[/usernames]</p>[usernames]Another Name Here[/usernames]</body></html>"
    'Named pattern
    Dim p = "\[usernames\](?<UserNames>.*?)\[/usernames\]"
    'Grab all of the matches
    Dim Matches = Regex.Matches(html, p, RegexOptions.IgnoreCase Or RegexOptions.Singleline)
    'Make sure we found something
    If Matches IsNot Nothing AndAlso Matches.Count > 0 Then
        'Loop through all of the matches
        For Each Match As Match In Matches
            'Make sure our sub-group was a success
            If Match.Groups("UserNames").Success Then
                Trace.WriteLine(Match.Groups("UserNames").Value)
            End If
        Next
    End If

答案 1 :(得分:1)

最好为每个实例解析文档。

匹配一个实例的正则表达式将是

/<usernames>([^<]+?)<\/usernames>/