繁体   English   中英

从字符串中提取特定的整数序列 Java

[英]Extract a specific sequence of integers from a string Java

我想从 Java 中的字符串中提取特定的整数序列

所以我想提取239从串1,和889从字符串2.我搜查,但我发现是使用正则表达式,并删除所有非数字。 但是,因为我不想让我不能使用,这里"1"中的"Name1"

import java.io.*;

public class Test1 {

    public static void main(String[] args){
        BufferedReader br = null;
        try{
                String s;
                br = new BufferedReader(new FileReader("C:/Users/i1234/Desktop/Workspace/Assign4/src/input1.txt"));
                while((s = br.readLine()) != null){
                    s = s.replaceAll("\\D+", "");
                    System.out.println(s);
                }
        }catch(IOException e){ //Exceptions handling
            e.printStackTrace();
        } finally{
            try{
                if (br != null){
                    br.close();
                } 
            }catch(IOException ex){
                ex.printStackTrace();
            }
        }
    }
}

输入文件是:

Name1 string 239

Name2 is a string 889

Word 432

输出是:

1239

2889

432

如果文件中的所有行都遵循相同的模式,则执行以下操作。

while((s = br.readLine()) != null){
    s = s.split(" ")[s.split(" ").length - 1];
    System.out.println(s);
}

如果数字后面有内容,您可以使用正则表达式单词边界:

while ((s = br.readLine()) != null) {
    Matcher m = Pattern.compile("\\b\\d+\\b").matcher(s);
    if (m.find()) {
        System.out.println(m.group());
    }
}

暂无
暂无

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

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