tags:

views:

72

answers:

5

Using regex. trying to get only the last x digits of the number and 0 padding where necessary

Consider the following input

1234
123
12
1

EDIT: These will appear individually as string values

i'm trying to make a regex expression (or several regex expressions, ideally just a single) yield

34
23
12
01

I'm a bit new to regex and backreferencing and still fumbling around a bit. any ideas on where to look or what could do this?

thanks

EDIT For clarification: To be used in .net's System.Text.Regex.Replace() function any of these values may come in as the input parameter.

EDIT: Thanks for the ideas everyone. It seems this cannot be done within regex. Sad as it is.

+1  A: 

If you must use regular expressions this can be done if you use a MatchEvaluator, but it would be better not to use regular expressions for this task.

Since you indicated that a solution that does not use regular expressions might be acceptable, here is one way to do it in C# that doesn't use regular expressions:

void Run()
{
    string s ="1234";
    s = lastXDigits(s, 3);
    Console.WriteLine(s);
}

string lastXDigits(string s, int x)
{
    if (s.Length < x)
    {
        return s.PadLeft(x, '0');
    }
    else
    {
        return s.Substring(s.Length - x);
    }
}

Result for each of your inputs:

234
123
012
001
Mark Byers
I think you need \d{0,x} or you'll miss anything with fewer than x digits.
cape1232
@cape1232: I didn't see the requirement that the padding should be variable. I'll update.
Mark Byers
I think i'm going to use this approach. seems i can't really do what i want with regex alone.
Beta033
A: 

what you can do is to use a .substring(int start, int length) and then format the string to be 2 characters long, but unless you specify the language, our hands are a bit tied.

npinti
A: 

This won't pad the zero, but seems to work (tested in JavaScript):

/[0-9]{1,2}$/
lxe
+1  A: 

Based on your other questions, I'm assuming that you're using VB.Net.

You don't need a regex; you can just use string manipulation:

Dim str As String

If str.Length > 2 Then str = str.Substring(str.Length - 2)
str = str.PadLeft(2, '0'c)
SLaks
+1 for non-regex approach (turns out that it was not a requirement after all).
Mark Byers
A: 

What language are you using? .. This might be easier without regex.

For example heres how you can do it in PHP:

$arr = array(1234,123,12,1);

foreach($arr as $num)
{
    echo '<br />'.str_pad(substr($num,-2), 2, "0", STR_PAD_LEFT);
}
John Isaacks