Is there are a simple way to ensure with RegEx that input String will contain exactly, let's say one 'a', five 'b, seven 'z' characters - with no order checking?
-
3What have you tried? Include your code. What problems did you encounter? – Jonathan Hall Nov 28 '18 at 14:43
-
Yes, there is. What have you tried? What didn't work? What did you get? What did you expect? What doesn't work with your code and where is it? – Toto Nov 28 '18 at 14:43
-
https://stackoverflow.com/questions/22411445/regex-match-specific-characters-in-any-order-without-more-occurrences-of-each-c – Freiheit Nov 28 '18 at 14:46
-
https://regex101.com/ is a great tool to try and test regexes enter your regex and then several strings to see what matches. For example a regex that matches on one of each character is https://regex101.com/r/UtoK45/1 – Freiheit Nov 28 '18 at 14:47
-
let's say if you want to make sure that there is only one 'a' in your input then you can use regex: "[.&&[^a]]*[a][.&&[^a]]* It's quite simple but when you want to add more "a" and more characters it becomes much more complicated to check it via that type of regex style – Ares02 Nov 28 '18 at 14:48
2 Answers
In Java you can use StringUtils.countMatches
as described here: How do I count the number of occurrences of a char in a String?
This is not a regex based solution but it is a Java solution. Several answers there show other techniques.

- 8,408
- 6
- 59
- 101
The "ordered" way to do your task using regex is as follows:
- Start with
^
anchor. - Then put 3 positive lookaheads for particular conditions (details below).
- And finally put
.*$
matching the whole string.
And now get down to particular conditions and respective lookaheads:
A single
a
:(?=[^a]*a[^a]*$)
- there should be:[^a]*
- A number of characters different thana
, possibly 0.a
- Then just a singlea
.[^a]*
- Then again a number of characters different thana
, possibly 0.$
- And finally the end of string.
Five times
b
:(?=[^b]*(?:b[^b]*){5}$)
. This timeb[^b]*
is the content of a non-capturing group, needed due to the quantifier after it.Seven times
z
:(?=[^z]*(?:z[^z]*){7}$)
. Like before, but this time the letter in question isz
and the quantifier is7
.
So the whole regex can look like below:
^(?=[^a]*a[^a]*$)(?=[^b]*(?:b[^b]*){5}$)(?=[^z]*(?:z[^z]*){7}$).*$
For a working example see https://regex101.com/r/gUxC2C/1
Try to experiment with the content, adding or removing a
, b
or z
and you will see appearing / disappearing match.

- 30,023
- 4
- 23
- 41