Regex to find out length
-
Lets say I want to "encrypt" the ID number 123456789 - add '*' to all the digits up to the last four - *****6789. A starting point is to replace .*(....) with *$1. But it would produce *6789, which is too short. How can I know how many chars the first .* matched?
-
Lets say I want to "encrypt" the ID number 123456789 - add '*' to all the digits up to the last four - *****6789. A starting point is to replace .*(....) with *$1. But it would produce *6789, which is too short. How can I know how many chars the first .* matched?
It depends which language and framework you're using. But a regex is almost certainly the wrong tool for this job. For example, in C# you might use something like this:
string input = "1234567890";
string output = string.Create(input.Length, input, static (buffer, input) =>
{
int pivot = buffer.Length - 4;
buffer[0..pivot].Fill('*');
input.AsSpan()[pivot..].CopyTo(buffer[pivot..]);
});
"These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer
-
Lets say I want to "encrypt" the ID number 123456789 - add '*' to all the digits up to the last four - *****6789. A starting point is to replace .*(....) with *$1. But it would produce *6789, which is too short. How can I know how many chars the first .* matched?
You could use a zero-length lookahead.
"1234345242342356789".replaceAll(/\d(?=\d{4})/g, "*")