Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to separate integer numbers from a string?

Tags:

java

parsing

I have a string

String exp = "7 to 10";

now I am keeping a condition that

if (exp.contains("to"))
{
    // here I want to fetch the integers 7 and 10
} 

How to separate 7 and 10 from the string 7 to 10 (parsed as Integer).

By using a delimiter I can obviously do it but I want to know how to do it this way?

like image 421
suganya Avatar asked Mar 29 '26 21:03

suganya


1 Answers

Using split:

    if (exp.contains(" to ")) {
        String[] numbers = exp.split(" to ");
        // convert string to numbers  
    }

Using regex:

    Matcher mat = Pattern.compile("(\\d+) to (\\d+)").matcher(exp);
    if (mat.find()) {
        String first = mat.group(1);
        String second = mat.group(2);
        // convert string to numbers
    }
like image 171
Sergii Lagutin Avatar answered Apr 01 '26 07:04

Sergii Lagutin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!