Question
Create strings with predefined conditions
Is there anything in java that does the opposite of regular expressions?
My task is: given a defined total length for a string and each position can only consist of predefined specific characters, generate all possible strings.
To give an example: I want to create all stings of length 3 where the positions are defined as
[ABC][123][XYZ]
This means that the first position can only be A, B or C
, the second position one of the numbers 1 to 3
and so on. Valid strings would therefore be
A1X
A1Y
A1Z
A2X
A2Y
A2Z
...
...
C3Z
For the length three I can of course use a nested loop. My problem is I don't know in advance how long the string has to be or how many valid characters each position has. Any ideas?
Code for length 3 and each position 3 possible chars:
public static void main(String[] args) {
String[] first = {"A", "B", "C"};
String[] second = {"1", "2", "3"};
String[] third = {"X", "Y", "Z"};
List<String> result = createStrings(first, second, third);
result.forEach(System.out::println);
}
static List<String> createStrings(String[] ... strs) {
String[] first = strs[0];
String[] second = strs[1];
String[] third = strs[2];
List<String> result = new ArrayList<>();
for (int i = 0; i < first.length; i++) {
for (int j = 0; j < second.length; j++) {
for (int k = 0; k < third.length; k++) {
result.add(first[i] + second[j] + third[k]);
}
}
}
return result;
}
I need something flexible, which works for all inputs. Or a way to dynamically create a nested loop depending on strs.length
which defines how many loops I need.