Getting variable in a pattern using Regex

  • Thread starter Thread starter Ya Ya
  • Start date Start date
Y

Ya Ya

Hi,
I have a string with some fixed text and variable text.
For example: "this is a fixed text THE NEEDED INFO more more fixed text".
How do I get the the variable text (THE NEEDED INFO) from this string ?
A simple example will help.

Thanks.
(e-mail address removed)
 
Dim txt As String
txt = "this is a fixed text THE NEEDED INFO more more fixed text"
txt = Mid(txt, 23, txt.Length - 22)

23 <- starting index
txt.Length - 22 <- size of your NEEDED INFO
 
Dim text As String = "One car red car blue car"
Dim pat As String = "(\w+)\s+(car)"
' Compile the regular expression.
Dim r As Regex = new Regex(pat, RegexOptions.IgnoreCase)
' Match the regular expression pattern against a text string.
Dim m As Match = r.Match(text)
Dim matchcount as Integer = 0
While (m.Success)
matchCount += 1
Console.WriteLine("Match" & (matchCount))
Dim i As Integer
For i = 1 to 2
Dim g as Group = m.Groups(i)
Console.WriteLine("Group" & i & "='" & g.ToString() & "'")
Dim cc As CaptureCollection = g.Captures
Dim j As Integer
For j = 0 to cc.Count - 1
Dim c As Capture = cc(j)
Console.WriteLine("Capture" & j & "='" & c.ToString() _
& "', Position=" & c.Index)
Next j
Next i
m = m.NextMatch()
End While


chanmm
 
Hi,
I have a string with some fixed text and variable text.
For example: "this is a fixed text THE NEEDED INFO more more fixed text".
How do I get the the variable text (THE NEEDED INFO) from this string ?
A simple example will help.

Assuming you want to match by the surrounding text (as opposed to
matching all case, or whatever)...


Private Function DoMatch(ByVal input As String) As String
Dim pattern As String = "fixed text ([\w ]+) more more fixed text"

Dim match As System.Text.RegularExpressions.Match = _
System.Text.RegularExpressions.Regex.Match(input, pattern)

If match.Length > 0 Then
Return match.Groups(1).Value
Else
Return Nothing
End If

End Function
 
Back
Top