tags:

views:

70

answers:

3

Given a string in the format: XXX999999v99 (where X is any alpha character and v is any numeric character and v is a literal v character) how can I get a regex to match the numeric characters following the v? So far I've got 'v\d\d' which includes the v but ideally I'd like just the numeric part.

As an aside does anyone know of a tool in which you can specify a string to match and have the regex generated? Modifying an existing regex is one thing but I find starting from scratch painful!

Edit: Re-reading this question I realise it reads like a homework assignment! However I can assure you it's not, the strings I'm trying to match represent product versions appended to product codes. The current code uses all sorts of substring expressions to retrieve the version part.

+3  A: 

You can try:

v(\d+)$
  • v : matches the literal v
  • \d: a single digit
  • \d+: one or more digits.
  • (): grouping that also remembers the matched part, which can be used later
  • $: end of line anchor
codaddict
When I try this the match includes the v character. Is it possible to remove this and just return the numeric part? Thanks for replying.
Simon
@Simon : When the regex finds a match, the first group always contains the full string that matched the regex. You should check the second group if you need to get only the captured part.
Thibault Falise
Duh, just realised - remove the v char from the regex!
Simon
+2  A: 

You need to use a capture group:

Regex.Match("XXX999999v99",@"v(\d+)").Groups[1].Value
SLaks
Be careful, if there is no match in the original string, this code will throw an exception when trying to access Groups[1].
Thibault Falise
+1  A: 

There are some great free tools for regex testing.

Try: regex powertoy

or: RegExr

There are also some paid programs like regex buddy

drewk
I've been using the online version of RegExr but I find it hard to get going with!
Simon