Clay Jensen
Clay Jensen

Reputation: 43

Regex pattern that supports account number with special character hyphen and after we should allow optional number pattern

I am using:

Pattern.compile("^[0-9\w?]")

It should allow both: 12345678, 12345678-00001

Can you suggest a valid pattern?

Upvotes: 0

Views: 147

Answers (1)

RavinderSingh13
RavinderSingh13

Reputation: 133545

With your shown samples, could you please try following.

^\d+(?:-\d+)?$

Here is the Online demo of above regex

Explanation: Adding detailed explanation for above.

^\d+   ##Checking if value starts from digits(1 or more occurrences) here.
(?:    ##Starting a non capturing group from here.
-\d+   ##Checking if it has -(hyphen) and followed by 1 or more digits.
)?$     ##Closing non capturing group here and keeping it optional to match OP's both cases at the end of the value.

Upvotes: 3

Related Questions