Returning the ordinal position of regex matches in the original string

2 views
Skip to first unread message

Sathyaish

unread,
May 10, 2009, 5:16:01 PM5/10/09
to Regex
For fun, I'm developing a utility that will take an input string and a
regex and will color highlight all matches of the regex in the
original string, alike the Find function in Firefox or IE 8, and some
popular browsers.

I am using C#. Does any member of the System.Text.RegularExpressions
namespace return the ordinal positions of the matches in the original
string? I also need their lengths.

Is there a way to get this information?

mkweaver

unread,
Jun 13, 2009, 1:55:06 PM6/13/09
to Regex
In VB.Net I'm doing this - hopefully it will point you in the right
direction:

001 Public Function GetDefuns(ByVal strFileText As String, ByRef
lspFile As LispFile) As Collection
002 ' Consider this: (?<!;)\(defun c:([^(]+)[^;]
+;+ *(.*)$
003 Dim objRegex As Regex = New Regex("(?<!;)\(defun ([^(]+)[^;]+;
(.*)$", RegexOptions.Multiline Or RegexOptions.IgnoreCase)
004 Dim colReturns As New Collection
005 objRegex.Matches(strFileText)
006 With objRegex
007 For Each objMatch As Match In .Matches(strFileText)
008 Dim objDefun As New Defun
009 With objDefun
010 .SourceFile = lspFile
011 .Name = objMatch.Groups.Item(1).Captures.Item(0).ToString
().Trim()
012 .ShortDescription = objMatch.Groups.Item(2).Captures.Item
(0).ToString().Trim()
013 .IsCommand = Left(.Name, 2).ToUpper = "C:"
014 .StartPoint = objMatch.Groups.Item(2).Captures.Item
(0).Index
015 End With
016 colReturns.Add(objDefun)
017

... snippage ...

121 Next
122 End With
123 Return colReturns
124 End Function

Note line 014 is getting the ordinal position of the start of the
second capture group.
Reply all
Reply to author
Forward
0 new messages