Regex replace followed by number.

Taylor Hillegeist via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Jun 1 09:01:47 PDT 2016


So I have ran into an issue where I want to replace a string with 
regex.

but i cant figure out how to replace items followed by a number.

i use "$1001" to do paste first match but this thinks I'm trying 
using match 1001
but if i try ${1}001 it gives me an error saying that it cant 
match the other "}"

perhaps D uses a different syntax but i couldn't find any 
documentation on the replace side.


The following code renames files.
arg 1 - path
arg 2 - regex match
arg 3 - regex replace

----------------------
import std.file;
import std.path;
import std.regex;
import std.range;
import std.stdio:writeln;

void main(string[] args){
	
	bool preview;
	Regex!char myreg;
	string replacment;
	
	if(!args[1].buildNormalizedPath.isValidPath){writeln("Path is 
invalid! ");   return;}
	try{myreg       = regex(args[2]);}
	    catch(RegexException e)                   {writeln("Invalid 
Regex command");return;}
	try{replacment  = args[3];}
	    catch(Exception e)                 {writeln("Needs 
replacment string");return;}
	if(args.length < 5){
		preview  = true;
		writeln("result is preview only add extra arg for action");
	}else{preview  = false;}

	size_t longest=0;
	foreach (string name; 
dirEntries(buildNormalizedPath(args[1].driveName(),args[1].stripDrive()) , SpanMode.shallow))
	{
		if(name.isFile){
			longest = (longest>name.baseName.length) ? longest : 
name.length;
		}
	}
	
	foreach (string name; 
dirEntries(buildNormalizedPath(args[1].driveName(),args[1].stripDrive()) , SpanMode.shallow))
	{
		if(name.isFile){
			if(preview){
				writeln("From:",name.baseName," 
".repeat(longest-name.baseName.length).join,"to:",replaceAll(name.baseName, myreg,replacment ));
			}else{
				std.file.rename(name,replaceAll(name, myreg,replacment ));
		    }
		}
	}
}
-----------------------------------------


More information about the Digitalmars-d-learn mailing list