I’ve these three regular expressions. They work individually but i would like to merge them in a single pattern.
regex1 = [0-9]{16}
regex2 = [0-9]{4}[-][0-9]{4}[-][0-9]{4}[-][0-9]{4}
regex3 = [0-9]{4}[ ][0-9]{4}[ ][0-9]{4}[ ][0-9]{4}
I use this method:
Pattern.compile(regex);
Which is the regex string to merge them?
You can use backreferences:
This will only match if the seperators are either all
\1means “this matches exactly what the first capturing group – expression in parentheses – matched”.Since
([ -]|)is that group, both other separators need to be the same for the pattern to match.You can simplify it further to: