What is the best way to dynamically create a regular expression by variable number of parameters?
E.g. if my regular expression is of the form:
String REGEX = "\\b(?:word1(?:(\\s+)word2(?:(\\s+)word3)?)?)";
I would like to dynamically create the regular expression string passing/replacing the wordX and I want to pass a variable number of words e.g. just 2 or perhaps 7.
I.e. to end up with:
REGEX = "\\b(?:cat(?:(\\s+)mouse(?:(\\s+)rain)?)?)";
in one call, and in another:
REGEX = "\\b(?:cat(?:(\\s+)mouse(?:(\\s+)rain(?:(\\s+)blue(?:(\\s+)?)?)?)?)?)";
An answer that regular expressions are not suited for these constructs could be accepted provided that it is well backed.
You can write a recursive function which will generate regex strings in the form of the first example you gave:
You will have to test and debug this code yourself, but it should give you the idea. (If you do find bugs, please edit this post for any others who come later.)