I would like to be able to merge two (maybe three) strings as shown below. Is this possible using a regex? (The base language I am using is Actionscript 3.0, but I can work with a more generic regex solution.)
The idea is that XYZ (non-dash) chars are fixed in place, with the dashes getting replaced with the new chars, as needed. Any additions are added as if a stack which skips around the fixed chars. I imagine using a 3rd string: ---XYZ--- to maintain the placeholders.
Re to comments
Masked text input is what I am looking for, but adding from the right rather than the left. The underscores represent placeholders for added chars. They will actually be seen on screen (unless replaced, of course).
An extensive example:
Preparation: set the string length: ---------
Preparation: set the fixed: ---XYZ---
Add char: ---XYZ--a
Add char: ---XYZ-ab
Add char: ---XYZabc
Add char: --aXYZbcd
Add char: -abXYZcde
Add char: abcXYZdef
Remove char: -abXYZcde
Remove char: --aXYZbcd
Remove char: ---XYZabc
Add multiple chars: abcXYZmno
Remove multiple chars: ---XYZabc
ANSWER
Based on @Charmander’s suggestion, here is a complete example:
var carr:Array = [];
function fillMaskChars(maskText:String, chars:String, pop:Boolean = false):String
{
var maskLen:int = maskText.match(/-/g).length;
if (pop)
{
carr.pop();
}
else if (carr.length < maskLen)
{
carr = carr.concat(chars.split('', maskLen - carr.length));
}
if (carr.length == 0)
{
return maskText;
}
var i = carr.length - maskLen - 1;
return maskText.replace(/-/g, function()
{
return carr[++i] || '-';
});
}
Some tests:
var characters:String = "oed";
var curMask:String = "--W-RK---";
var outText:String = maskChars(curMask, characters);
trace(outText);
characters = "!";
outText = maskChars(curMask, characters);
trace(outText);
characters = "abcdefghij";
outText = maskChars(curMask, characters);
trace(outText);
outText = maskChars(curMask, "", true);
trace(outText);
outText = maskChars(curMask, "", true);
trace(outText);
outText = maskChars(curMask, "", true);
trace(outText);
outText = maskChars(curMask, "", true);
trace(outText);
I think you will find an array more appropriate. I’m afraid I have no experience in ActionScript, but it should not be difficult to translate from JavaScript.
It is passed an array of characters, which you may manipulate as necessary. For example: