简体   繁体   English

字符串中的数字

[英]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. 在那个for循环中,我希望能够浏览字符串并仅找到前两个数字。 How do I do that? 我怎么做?

Example: 例:

str= 1 b 3 s 4

Print: 1 3 打印: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. \\d+ (用String文字表示为"\\\\d+" )是匹配一个或多个数字的正则表达式。

m.find() finds the next match, returning whether it found the match. m.find()查找下一个匹配项,返回是否找到匹配项。

m.group() returns the matched substring. m.group()返回匹配的子字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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