Zachary Scott
Zachary Scott

Reputation: 21172

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.

Upvotes: 0

Views: 410

Answers (2)

Brian Roach
Brian Roach

Reputation: 76898

You don't. You either capture in 3 groups and concatenate them into a single string, or do a search-and-replace to get rid of the dashes in your single named group.

Upvotes: 2

BoltClock
BoltClock

Reputation: 723528

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("-", "");

Upvotes: 4

Related Questions