Skip to Content
Regular Expressions Cookbook
book

Regular Expressions Cookbook

by Jan Goyvaerts, Steven Levithan
May 2009
Intermediate to advanced
510 pages
15h
English
O'Reilly Media, Inc.
Content preview from Regular Expressions Cookbook

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 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Regular Expressions Cookbook, 2nd Edition

Regular Expressions Cookbook, 2nd Edition

Jan Goyvaerts, Steven Levithan

Publisher Resources

ISBN: 9780596802837Catalog PageErrata