Java regex to define strings with more digits than digits

How can I identify strings containing more digits than non-regular expression (Pattern) digits in Java? Thanks.

+1


a source to share


6 answers


It is not an ordinary language and therefore it cannot be captured by vanilla regex. It's possible anyway, but it will almost certainly be easier not to use a regex:



public static boolean moreDigitsThanNonDigits(String s) {
    int diff = 0;
    for(int i = 0; i < s.length(); ++i) {
        if(Character.isDigit(s.charAt(i))) ++diff;
        else --diff;
    }
    return diff > 0;
}

      

+12


a source


You can't write a regexp that does this. But you already said that you are using Java, why not mix it up in a little code?



public boolean moreDigitsThanNonDigits(String input) {
    String nonDigits = input.replace("[0-9]","");
    return input.length() > (nonDigits.length * 2);
}

      

+10


a source


Regular expressions are conceptually incapable of doing this. They are equivalent to formal languages ​​or (regular) automata. They have no concept of memory (or stack), so they cannot count the occurrences of characters. The next extension in terms of expressiveness is push-down automatons (or stack machines), which correspond to context-free grammars. Before writing such a grammar for this task, using a method like the one moreDigitsThanNonDigits

above would be appropriate.

+3


a source


As mentioned, the language in question is not regular and cannot be detected using a regular expression.

I'll give you another way to count the number of digits and the number of digits in a string using regex !!

You can use the method String.replaceAll

to remove all non-digit digits in the input string. The length of the resulting string will be the number of digits in the input.

Similarly, you can remove all digits in the input string, and the length of the resulting string will be the number of non-digit digits in the input string.

public static boolean test(String str) {
         int numDigits = str.replaceAll("\\D","").length();
         int numNonDigits = str.replaceAll("\\d","").length();

         return numDigits > numNonDigits;
}

      

Perfect link

+1


a source


I'm not sure if using regular expressions would be the best solution here.

0


a source


regex alone cannot (since they don't count anything); but if you want to use them, just use two replacements: one that removes all digits and one that keeps them. then compare the lengths of the result strings.

of course I would rather use Dave's answer.

0


a source







All Articles