Coder14
Coder14

Reputation: 1277

Access multiple captures of one capture group in substition string

Suppose I have the regex (\d)+. In .Net I can access all captures of this capture group using the match.Groups[1].Captures.

Can I also access these captures in a substition string?

So for example for the input string 523, I need to use 5, 2 and 3 in my substition string (and not just 3, which is $1).

Upvotes: 0

Views: 43

Answers (2)

UlfR
UlfR

Reputation: 4395

If you intend to capture the digits each in its separate capturing group then you need to actually make a separate capturing groups for every digits like this:

(\d)(\d)(\d)

NOTE: This does not scale very well and you could not match numbers of any other length than 3 digits. In other words, no math on either 23 or 345667!

An good page with a long and detailed explanation why this cant be done as (\d)+ can be found here: https://www.regular-expressions.info/captureall.html

So if this is indeed what you want then you need to craft your own loop that searches the string for every digit separately.


If you on the other hand need to capture the number and not the individual digits then you simply put the +sign in the wrong position. I think you should write:

(\d+)

Upvotes: 1

Theo
Theo

Reputation: 61148

I think the OP wants to get every single digit match separately. Perhaps this will help you then:

<!-- language: lang-vb -->

' Create a list to put the resulting matches in
Dim ResultList As StringCollection = New StringCollection()
Dim RegexObj As New Regex("(\d)")
Dim MatchResult As Match = RegexObj.Match(strName)
While MatchResult.Success
    ResultList.Add(MatchResult.Groups(1).Value)
    ' Console.WriteLine(MatchResult.Groups(1).Value)
    MatchResult = MatchResult.NextMatch()
End While

Upvotes: 0

Related Questions