Skip to content

Instantly share code, notes, and snippets.

@d4vsanchez
Created June 18, 2022 17:43
Show Gist options
  • Save d4vsanchez/e9721af978eccf36848f075bc4d3041b to your computer and use it in GitHub Desktop.
Save d4vsanchez/e9721af978eccf36848f075bc4d3041b to your computer and use it in GitHub Desktop.
Simple calculator in Rust
use std::str::FromStr;
use regex::Regex;
const ADDITION: &str = "(\\d+)\\s*?(\\+)\\s*?(\\d+)";
const SUBTRACTION: &str = "(\\d+)\\s*?(\\-)\\s*?(\\d+)";
const MULTIPLICATION: &str = "(\\d+)\\s*?(\\*)\\s*?(\\d+)";
const DIVISION: &str = "(\\d+)\\s*?(/)\\s*?(\\d+)";
fn main() {
// Traer datos del usuario
println!("Por favor introduce tu expresión: ");
let mut expression = String::new();
std::io::stdin().read_line(&mut expression).unwrap();
expression = perform_operation(expression, MULTIPLICATION);
expression = perform_operation(expression, DIVISION);
expression = perform_operation(expression, ADDITION);
expression = perform_operation(expression, SUBTRACTION);
// Mostrar el resultado
println!("El resultado es: {}", expression);
}
fn perform_operation(mut expression: String, operation: &str) -> String {
let operation_regex = Regex::from_str(operation).unwrap();
loop {
let caps = operation_regex.captures(expression.as_str());
if caps.is_none() {
break;
}
let caps = caps.unwrap();
let cap_expression = caps.get(0).unwrap().as_str();
let left_value: i32 = caps.get(1).unwrap().as_str().parse().unwrap();
let operation: &str = caps.get(2).unwrap().as_str();
let right_value: i32 = caps.get(3).unwrap().as_str().parse().unwrap();
let result = match operation {
"+" => left_value + right_value,
"-" => left_value - right_value,
"*" => left_value * right_value,
"/" => left_value / right_value,
_ => 0,
};
expression = expression.replace(cap_expression, &result.to_string());
}
expression
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment