asp.netregex

Regex: Capture only numbers with a X-XXXXX-XXXXX pattern (Skip unwanted characters)?


I have a number of 0-12345-67890 and I want to capture 0123456789 in a named capture group. I got this far:

@"(?<upc>\d-\d{5}-\d{5})"

Which captures the string as-is. How do you skip the dashes while grabbing the number as a single named group? BTW, this is ASP.NET Regex.


Solution

  • I don't believe you can do this with a regex match to a single backreference. Either you match the dashes, or you don't (and capture nothing).

    You'll have to remove them manually with Replace() after capturing the numbers:

    var number = m.Groups["upc"].Replace("-", "");