0
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

user243872
  • 351
  • 1
  • 2
  • 7

1 Answers1

1

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.

Paul Draper
  • 78,542
  • 46
  • 206
  • 285