Java regex to define strings with more digits than digits
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;
}
a source to share
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.
a source to share
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;
}
a source to share