开发者

VB.Net Regex...extracting a value

How in VB.Net can I extract the value from a string using the RegularExpressions class? For example, say I have the string:

[Mon Jan 4 2011] Blah Blah2 Other开发者_运维百科 text

and I want to return the "Mon Jan 4 2011" portion in to a variable. I thought you would use the "Regex.Replace" method but I can't seem to figure out how to extract the portion of the string I want.


In this case, I don't think you need to replace the text, you need to match the text instead.

Regex.Match(input, "(?<=\[)[^\]]+").Value

This takes all the text from right after the first [ up until the next ]. Edit: missed a square bracket.


You can use match groups - specifically name the part of the expression you want and reference it by name:

Imports System.Text.RegularExpressions

Module Example
   Public Sub Main()
      Dim pattern As String = "\[(?<datestring>[^\]]+)\]"
      Dim input As String = "[Mon Jan 4 2011] Blah Blah2 Other text"
      Dim match As Match = Regex.Match(input, pattern)

      ' Get the first named group.
      Dim group1 As Group = match.Groups.Item("datestring")
      Console.WriteLine("Group 'datestring' value: {0}", If(group1.Success, group1.Value, "Empty"))
   End Sub
End Module


Try with regex:

\x5B([^\x5D]+)


you can also use this code to achieve your goal:

    Dim str As String = "[Mon Jan 4 2011] Blah Blah2 Other text"
    Dim m As Match = Regex.Match(str, "\[(?<tag>[^]]*)")
    If (m.Success) Then
        Debug.Print(m.Result("${tag}"))   ' Check "Output Window"
    End If

In this code matched result will be stored in named group tag and will be used accordingly.


i'm suggesting you to follow the article here: http://www.codeproject.com/Articles/9099/The-30-Minute-Regex-Tutorial

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜