3.8. Determine the Position and Length of the Match
Problem
Instead of extracting the substring matched by the regular expression, as shown in the previous recipe, you want to determine the starting position and length of the match. With this information, you can extract the match in your own code or apply whatever processing you fancy on the part of the original string matched by the regex.
Solution
C#
For quick one-off matches, you can use the static call:
int matchstart, matchlength = -1; Match matchResult = Regex.Match(subjectString, @"\d+"); if (matchResult.Success) { matchstart = matchResult.Index; matchlength = matchResult.Length; }
To use the same regex repeatedly, construct a Regex
object:
int matchstart, matchlength = -1; Regex regexObj = new Regex(@"\d+"); Match matchResult = regexObj.Match(subjectString).Value; if (matchResult.Success) { matchstart = matchResult.Index; matchlength = matchResult.Length; }
VB.NET
For quick one-off matches, you can use the static call:
Dim MatchStart = -1 Dim MatchLength = -1 Dim MatchResult = Regex.Match(SubjectString, "\d+") If MatchResult.Success Then MatchStart = MatchResult.Index MatchLength = MatchResult.Length End If
To use the same regex repeatedly, construct a Regex
object:
Dim MatchStart = -1 Dim MatchLength = -1 Dim RegexObj As New Regex("\d+") Dim MatchResult = Regex.Match(SubjectString, "\d+") If MatchResult.Success Then MatchStart = MatchResult.Index MatchLength = MatchResult.Length End If
Java
int matchStart, matchLength = -1; Pattern ...
Get Regular Expressions Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.