如何从字符串中提取数字 [英] How to extract numbers from a string

查看:128
本文介绍了如何从字符串中提取数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

String a = "sin(23)+cos(4)+2!+3!+44!";
a.replaceAll("\D"); //Not working it is only extracting Digits 

我想提取<$ c的数字$ c>!仅限(示例 2 3 ),然后必须保存在 int [] 中,必须再次将这些数字粘贴到 2! 3!存在。

I want to extract the numbers which are with ! only (example 2 and 3), then have to save it in a int[] and have to again paste those numbers at the place where 2! and 3! exist.

推荐答案

使用正则表达式找到你想要的东西:

Use regular expression to find what you want:

String a = "sin(23)+cos(4)+2!+3!+44!";

Pattern pattern = Pattern.compile("\\d+!"); //import java.util.regex.Pattern
Matcher matcher = pattern.matcher(a);       //import java.util.regex.Matcher
while (matcher.find()) {
    System.out.print("Start index: " + matcher.start());
    System.out.print(" End index: " + matcher.end() + " -> ");
    System.out.println(matcher.group());
}

输出:

Start index: 15 End index: 17 -> 2!
Start index: 18 End index: 20 -> 3!
Start index: 21 End index: 24 -> 44!






进一步改善:

使用以下内容,您可以使用<$ c $直接转换 matcher.group(1)返回值c> Integer.parseInt():

With the following, you can cast the matcher.group(1) return value directly using Integer.parseInt():

Pattern pattern = Pattern.compile("(\\d+)!");
...
    System.out.println(matcher.group(1));

输出:

Start index: 15 End index: 17 -> 2
Start index: 18 End index: 20 -> 3
Start index: 21 End index: 24 -> 44






你能弄清楚剩下的吗?您可以使用索引值替换原始字符串中的匹配项,但确保从最后一个字符串开始。


Can you figure out the rest? You could use the index values to replace the matches in the original string, but be sure to start from the last one.

这篇关于如何从字符串中提取数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆