Results 1 to 5 of 5

Thread: can we do this in regular expression?

Threaded View

  1. #4
    Hyperactive Member
    Join Date
    Apr 2011
    Location
    England
    Posts
    421

    Re: can we do this in regular expression?

    Hi,

    You will struggle to do this without looking over your sentence more than once. Regex cannot step backwards to look at substrings that have already been matched.

    If you would like to stick with Regex then you could do something like this:
    VB.NET Code:
    1. Dim str As String = "This is a test"
    2. Dim str2 As String = str.Remove(0, str.IndexOf(" ") + 1)
    3.  
    4. Dim Results As MatchCollection = Regex.Matches(str, "\b\w+\b\s?\b\w+\b")
    5. Dim Results2 As MatchCollection = Regex.Matches(str2, "\b\w+\b\s?\b\w+\b")
    6.  
    7. Dim output As String = Nothing
    8.  
    9. For i As Integer = 0 To Results.Count - 1
    10.     output += Results.Item(i).Value & vbCrLf
    11.     If i <= Results2.Count - 1 Then
    12.         output += Results2.Item(i).Value & vbCrLf
    13.     End If
    14. Next
    15.  
    16. MsgBox(output)
    Although you should be able to write a better function to achieve the same goal using different methods e.g. String.Split, For-Next and Concatenation.

    Hope this helps
    Last edited by JayJayson; Jul 15th, 2011 at 12:31 PM.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width