简体   繁体   中英

Numbers from string

public void check(String str){
    for(int i =0; i<str.length(); i++){
    //Print only the numbers    
    }
}

In that for loop I want to be able to look through the string and find just the first two numbers. How do I do that?

Example:

str= 1 b 3 s 4

Print: 1 3

This works for numbers that are more than one digit.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public void check(String str) {
    Matcher m = Pattern.compile("\\d+").matcher(str);
    for(int n = 0; n < 2 && m.find(); n++)  {
        System.out.println(m.group());
    }
}

Explanation:

\\d+ (written in a String literal as "\\\\d+" ) is a regular expression that matches one or more digits.

m.find() finds the next match, returning whether it found the match.

m.group() returns the matched substring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM