Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RegEx - Take all numeric characters following a text character

Tags:

.net

regex

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.

like image 384
Simon Avatar asked Mar 23 '10 16:03

Simon


People also ask

What does ?= * Mean in regex?

?= is a positive lookahead, a type of zero-width assertion. What it's saying is that the captured match must be followed by whatever is within the parentheses but that part isn't captured. Your example means the match needs to be followed by zero or more characters and then a digit (but again that part isn't captured).

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What does \d include in regex?

Decimal digit character: \d \d matches any decimal digit. It is equivalent to the \p{Nd} regular expression pattern, which includes the standard decimal digits 0-9 as well as the decimal digits of a number of other character sets.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.


2 Answers

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
like image 87
codaddict Avatar answered Oct 20 '22 17:10

codaddict


You need to use a capture group:

Regex.Match("XXX999999v99",@"v(\d+)").Groups[1].Value
like image 36
SLaks Avatar answered Oct 20 '22 18:10

SLaks