Checking if string contains substring and printing whole line

So I need to check if the string contains a substring and print the whole line which contains this substring.

let string = "<button>something</button>
<span>164 Sales</span>"

I need to get the number of sales, but because it can change, I cannot check where it is.

This computes the first line containing "Sales" in an Option, storing None if no line contains "Sales.

let line_with_sales = string.lines()
    .filter(|line| line.contains("Sales"))
    .next();

I am new to rust, how can I print it ?

This should work:

println!("{:?}", line_with_sales);

Another option is to crash the program when there is no line containing "Sales". In that case, the program would look like this:

let line_with_sales = string.lines()
    .filter(|line| line.contains("Sales"))
    .next()
    .unwrap(); // <-- this line crashes the program if there is no such line

println!("{}", line_with_sales);
2 Likes

Thank you