paolo2988
paolo2988

Reputation: 867

Regular expression Java Merge Pattern

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?

Upvotes: 0

Views: 1004

Answers (2)

phant0m
phant0m

Reputation: 16905

You can use backreferences:

[0-9]{4}([ -]|)([0-9]{4}\1){2}[0-9]{4}

This will only match if the seperators are either all

  • spaces
  • hyphens
  • blank

\1 means "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:

\d{4}([ -]|)(\d{4}\1){2}\d{4}

Upvotes: 5

Duncan Jones
Duncan Jones

Reputation: 69339

The following should match anything the three patterns match:

regex = [0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}

That is, I'm assuming you are happy with either a hyphen, a space or nothing between the numbers?

Note: this will also match situations where you have any combination of the three, e.g.

0000-0000 00000000

which may not be desired?


Alternatively, if you need to match any of the three individual patterns then just concatenate them with |, as follows:

([0-9]{16})|([0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4})|([0-9]{4} [0-9]{4} [0-9]{4} [0-9]{4})

(Your original example appears to have unnecessary square brackets around the space and hyphen)

Upvotes: 1

Related Questions