How to remove all characters from a string, except the integers?

BoQsc vaidas.boqsc at gmail.com
Fri Mar 4 08:05:06 UTC 2022


On Thursday, 3 March 2022 at 12:14:13 UTC, BoQsc wrote:
> I need to check if a string contains integers,
> and if it contains integers, remove all the regular string 
> characters.
> I've looked around and it seems using regex is the only closest 
> solution.
>
> ```
> import std.stdio;
>
> void main(string[] args){
>
> 	if (args.length > 1){
> 	
> 		write(args[1]); // Needs to print only integers.
> 		
> 	} else {
> 		write("Please write an argument.");
> 	}
> }
> ```
#### Regular expression solution
```
import std.stdio;
import std.regex;
import std.string: isNumeric;
import std.conv;

void main(string[] args){

	if (args.length > 1){
	
		writeln(args[1]); // Needs to print only integers.
		
		string argument1 = args[1].replaceAll(regex(r"[^0-9.]","g"), 
"");
		if (argument1.isNumeric){
			writeln(std.conv.to!uint(argument1));
		} else {
			writeln("Invalid value: ", args[1]," (must be int integer)");
		}
		
	} else {
		write("Please write an argument.");
	}
}
```


More information about the Digitalmars-d-learn mailing list