user1158745
user1158745

Reputation: 2490

java string matching with regex

I have a specific key i need to match. The key is 10 set's of 4 separated by a dash. The combination can be a combination of letters or numbers.

Example.

aa11-bb22-cc33-44dd-55ee-66ff-gg77-hh88-99ii-jj10

I just want to validate the pattern being 10 sets of 4 separated by a dash.

Probably match this via regex, but I don't know how.

Any help would be appreciated.

Upvotes: 1

Views: 72

Answers (3)

Jigish
Jigish

Reputation: 1784

([a-zA-Z0-9]{4}-){9}[a-zA-Z0-9]{4}

Here's the regex in action: http://regex101.com/r/xR1wV3/1

Explanation:

  1. [a-zA-Z0-9] --> any character from a to z, A to Z and 0 to 9
  2. [a-zA-Z0-9]{4} --> {4} indicates exactly 4. So [a-zA-Z0-9]{4} means exactly 4 characters
  3. [a-zA-Z0-9]{4}- --> add a dash (-) at the end to match for dash separators. This should match with aa11- for example
  4. ([a-zA-Z0-9]{4}-) --> put #3 into parenthesis
  5. ([a-zA-Z0-9]{4}-){9} --> add {9} to the parenthesis to specify that this pattern repeat 9 times
  6. ([a-zA-Z0-9]{4}-)[a-zA-Z0-9]{4} --> add a [a-zA-Z0-9]{4} at the end to match the last set of 4 characters (same as #2 above)

Upvotes: 1

Bohemian
Bohemian

Reputation: 425318

You could do it like this:

(?!.*_)(\w{4}-){9}\w{4}

This makes use of the fact that \w means "any letter, number or underscore" and the negative look ahead prevents the underscore.

Upvotes: 0

vks
vks

Reputation: 67988

^[a-zA-Z0-9]{4}(?:-[a-zA-Z0-9]{4}){9}$

Try this.See demo.

http://regex101.com/r/kP8uF5/11

Upvotes: 4

Related Questions