我想在字符串中的每个数字左侧填充零(必须是8位数字)。
例如:
asd 123 rete > asd 00000123 rete
4444 my text > 00004444 my text
能否使用正则表达式来实现此操作?特别是用Regex.Replace()
函数是否可行?
请注意,不同数字的零的数量可能不同。我的意思是填充后的数字必须为8位数。
我想在字符串中的每个数字左侧填充零(必须是8位数字)。
例如:
asd 123 rete > asd 00000123 rete
4444 my text > 00004444 my text
能否使用正则表达式来实现此操作?特别是用Regex.Replace()
函数是否可行?
请注意,不同数字的零的数量可能不同。我的意思是填充后的数字必须为8位数。
Microsoft已经为此内置了函数:
someString = someString.PadLeft(8, '0');
这里有一篇关于MSDN的文章。
要使用正则表达式,可以像这样做:
string someText = "asd 123 rete";
someText = Regex.Replace(someText, @"\d+", n => n.Value.PadLeft(8, '0'));
虽然这篇帖子已经有点老了,但或许仍有人需要。
Nickon想使用正则表达式,为什么呢?也许只是为了好玩。我需要在SQL中进行内联替换,所以调用了一些自制的SQL函数来调用C#正则表达式。
我需要填充的内容看起来像这样:
abc 1.1.1
abc 1.2.1
abc 1.10.1
and I wanted:
abc 001.001.001
abc 001.002.001
abc 001.010.001
所以我可以按字母顺序对其进行排序。
到目前为止,我找到的唯一解决方案是分两步进行填充和截断以达到正确的长度。我不能使用 Lambda,因为这是在 SQL 中,而且我还没有准备好这些函数。
//This pads any numbers and truncates it to a length of 8
var unpaddedData = "...";
var paddedData = Regex.Replace(unpaddedData , "(?<=[^\d])(?<digits>\d+)",
"0000000${digits}");
var zeroPaddedDataOfRightLength = Regex.Replace(paddedData ,"\d+(?=\d{8})","");
解释:
(?<=[^\d])(?<digits>\d+)
(?<=[^\d]) Look behind for any non digit, this is needed if there are
more groups of numbers that needs to be padded
(?<digits>\d+) Find the numbers and put them in a group named digits to be
used in the replacement pattern
0000000${digits} Pads all the digits matches with 7 zeros
\d+(?=\d{8}) Finds all digits that are followed by at exactly 8 digits.
?= Doesn't capture the 8 digits.
Regex.Replace(...,"\d+(?=\d{8})","")
Replaces the leading digits with nothing leaving the last 8.
如果您对正则表达式没有任何依赖,只需使用格式化字符串:
static void Main(string[] args)
{
string myCC = "4556364607935616";
string myMasked = Maskify(myCC);
Console.WriteLine(myMasked);
}
public static string Maskify(string cc)
{
int len = cc.Length;
if (len <= 4)
return cc;
return cc.Substring(len - 4).PadLeft(len, '#');
}
只需将“#”替换为0或“0”即可。 希望这有所帮助:)