May 2009
Intermediate to advanced
510 pages
15h
English
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.
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;
}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 IfTo 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 Ifint matchStart, matchLength = -1; Pattern ...