2016-08-03 131 views
-8

我想要一个条件,只有如果一个字符串中包含更多的四位数字,并且如果字符串中少于四位数字是假的,我尝试过正则表达式像/ \ d {4} /,需要帮助如何检查一个字符串是否包含多个数字(java)?

+1

@kruti您可能的重复根本不是重复的 –

+1

“没有运气”不足以说明您遇到的问题。 – khelwood

+0

可能重复的[正则表达式计数不包括空格的位数](http://stackoverflow.com/questions/23978695/regex-count-number-of-digits-excluding-space) – Rupsingh

回答

0

以下模式会匹配包含至少4个数字的字符串:

(.*?\d){4, } 
+0

不,它是一个正则表达式模式。如何将它集成到Java中不应该是问题 –

1
public static void main(String[] args) { 
    String toCheck1 = "assg3asgasgas123aassag3"; 
    String toCheck2 = "aasdasfasfs"; 
    System.out.println(String.format("more then 4 number in \"%s\" - %s", toCheck1, moreThen4NumbersInString(toCheck1))); 
    System.out.println(String.format("more then 4 number in \"%s\" - %s", toCheck2, moreThen4NumbersInString(toCheck2))); 
} 

private static boolean moreThen4NumbersInString(String string) { 
    int numberOfNumbers = 0; 
    for (int i = 0; i < string.length(); i++) { 
     if (Character.isDigit(string.charAt(i))) { 
      numberOfNumbers++; 
      if (numberOfNumbers > 4) { 
       return true; 
      } 
     } 
    } 
    return false; 
} 

输出:

更然后4号在 “assg3asgasgas123aassag3” - 真更然后4在 “aasdasfasfs”号 - 假

+1

在达到阈值后不必再继续计算......(只是说) – Fildor

+0

@Fildor固定那个 – Divers

0

转换的stringchar[]for - 通过数组中的所有元素进行循环,并计数int count中的数字编号。就这么简单

0

你的表达需要四位数的顺序。还有我的是数字之间的一些其他字符,所以要求“数字和可选的东西”至少四次:

(?:\d.*?){4,} 

演示:https://regex101.com/r/kZ7iZ9/2

+0

“。*?”必须位于数字的前面 –

+0

@RafaelAlbert,除了'\ d。*?'以外的任何一种方式似乎都更有效。 –

+0

取决于模式是否必须匹配开头或者不匹配,因此使用的方法。 –

0

在这里,你走了样:

package com.company.misc; 

import java.util.regex.Matcher; 
import java.util.regex.Pattern; 

public class RegexSample { 

    public static void main(String[] args) { 
     String regex = "(.*?\\d){4,}"; 
     //(.*?\d){4, } do not use this, compilation error 
     String input = "test2531"; 
     Pattern pattern = Pattern.compile(regex); 
     Matcher matcher = pattern.matcher(input); 

     boolean isMatched = matcher.matches(); 
     System.out.println(isMatched); 

    } 
} 

希望我已经给出了你的用例的例子。

相关问题