Using regex to crop the last few digits

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

Consider the next entry

1234 123 12 1 

EDIT: they will be displayed individually as string values

I'm trying to make a regex expression (or multiple regex expressions, ideally just one)

 34 23 12 01 

I'm a little new to regex and callback and still staggering a bit. any ideas on where to look or what can be done?

thanks

EDIT To clarify: For use in .net System.Text.Regex.Replace (), any of these values ​​may be included as an input parameter.

EDIT: Thanks to everyone for the ideas. This seems to be impossible to do in regular expression. Sad as it is.

+4
source share
5 answers

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

Since you pointed out that a solution that doesn't 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); } } 

The result for each of your inputs:

  234
 123
 012
 001
+1
source

Based on your other questions, I assume that you are using VB.Net.

You do not need a regular expression; 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) 
+1
source

what you can do is use .substring(int start, int length) and then format the string up to two characters long, but if you don't specify the language, our hands are a bit tied.

0
source

This will not fill in zero, but it seems to work (tested in JavaScript):

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

What language do you use? .. It could be easier without regular expression.

For example, how can you do this 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
source

Source: https://habr.com/ru/post/1315975/


All Articles