开发者

using regex to trim off last few digits

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 开发者_Go百科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.


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


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)


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.


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

/[0-9]{1,2}$/


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);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜