本文介绍了检查String是否包含数字Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在编写一个程序,用户按以下格式输入字符串:
I'm writing a program where the user enters a String in the following format:
"What is the square of 10?"
- 我需要检查字符串中是否有数字
- 然后只提取数字。
- 如果我使用
.contains(\\\\ +)
或.contains([ 0-9] +)
,无论输入是什么,程序都无法在String中找到数字,但.matches(\\d + )
仅在只有数字时才有效。
- I need to check that there is a number in the String
- and then extract just the number.
- If i use
.contains("\\d+")
or.contains("[0-9]+")
, the program can't find a number in the String, no matter what the input is, but.matches("\\d+")
will only work when there is only numbers.
我可以使用什么作为查找解决方案和提取?
What can I use as a solution for finding and extracting?
推荐答案
我选择的解决方案如下:
The solution I went with looks like this:
Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);
Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);
if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}
我确定这不是一个完美的解决方案,但它符合我的需求。谢谢大家的帮助。 :)
I'm sure it's not a perfect solution, but it suited my needs. Thank you all for the help. :)
这篇关于检查String是否包含数字Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!