gpt4 book ai didi

java - 仅从字符串中提取数字

转载 作者:行者123 更新时间:2023-11-29 03:11:37 24 4
gpt4 key购买 nike

假设我有一个包含以下内容的字符串:hello 14:12

现在我只想提取数字并在两个变量中有两个单独的值,如下所示:first_num 值应该是 int,即 first_num = 14,第二个变量应该在冒号后存储数字 (:) 即 second_num = 12。

最佳答案

可以使用正则表达式来解决问题

public static List<Integer> extractNumbers(String s){       
List<Integer> numbers = new ArrayList<Integer>();

Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher(s);

while(m.find()){
numbers.add(Integer.parseInt(m.group()));
}
return numbers;
}

关于java - 仅从字符串中提取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29053040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com