Dua*_*ane 94 java regex string
我正在编写一个程序,用户按以下格式输入字符串:
"What is the square of 10?"
Run Code Online (Sandbox Code Playgroud)
.contains("\\d+")或者.contains("[0-9]+"),程序在String中找不到数字,无论输入是什么,但.matches("\\d+")只有在只有数字的情况下才能工作.我可以使用什么作为查找和提取的解决方案?
Evg*_*eev 208
试试这个
str.matches(".*\\d.*");
Run Code Online (Sandbox Code Playgroud)
Saj*_*tta 26
如果你想从输入字符串中提取第一个数字,你可以 -
public static String extractNumber(final String str) {
if(str == null || str.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
boolean found = false;
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
sb.append(c);
found = true;
} else if(found){
// If we already found a digit before and this char is not a digit, stop looping
break;
}
}
return sb.toString();
}
Run Code Online (Sandbox Code Playgroud)
例子:
对于输入"123abc",上面的方法将返回123.
对于"abc1000def",1000.
对于"555abc45",555.
对于"abc",将返回一个空字符串.
Mal*_*tty 10
s=s.replaceAll("[*a-zA-Z]", "") 替换所有字母表
s=s.replaceAll("[*0-9]", "") 取代所有数字
如果你做了以上两次替换,你将得到所有特殊的字符串
如果你只想从a中提取整数 String s=s.replaceAll("[^0-9]", "")
如果你只想从a中提取字母 String s=s.replaceAll("[^a-zA-Z]", "")
快乐编码:)
Ish*_*aan 10
我找不到一个正确的模式.请按照以下指南获取小巧而甜蜜的解决方案.
String regex = "(.)*(\\d)(.)*";
Pattern pattern = Pattern.compile(regex);
String msg = "What is the square of 10?";
boolean containsNumber = pattern.matcher(msg).matches();
Run Code Online (Sandbox Code Playgroud)
我认为它比正则表达式更快.
public final boolean containsDigit(String s) {
boolean containsDigit = false;
if (s != null && !s.isEmpty()) {
for (char c : s.toCharArray()) {
if (containsDigit = Character.isDigit(c)) {
break;
}
}
}
return containsDigit;
}
Run Code Online (Sandbox Code Playgroud)
小智 8
下面的代码足以"检查字符串是否包含Java中的数字"
Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");
if(m.find()){
System.out.println("Hello "+m.find());
}
Run Code Online (Sandbox Code Playgroud)
Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);
Run Code Online (Sandbox Code Playgroud)
我使用的解决方案如下所示:
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));
}
Run Code Online (Sandbox Code Playgroud)
我确定这不是一个完美的解决方案,但它满足了我的需求。谢谢大家的帮助。:)