Home > front end >  Java Regex only upper case and numbers with predefined format
Java Regex only upper case and numbers with predefined format

Time:02-01

I have problem with my Java regex. I am testing it here (https://regex101.com/) and it looks like I am not good with regex :(

Regex should look like this: TR12H4-030-485

  1. TR12H4-> Only upper case and numbers plus characters allowed. 6 chars long
  2. 030-> only numbers. 3 chars long
  3. 485-> Only numbers. 3 chars long
  4. Should be like XXXXXX-XXX-XXX with minus

Can someone give me good hints? Thank you

CodePudding user response:

Here's the solution with every step explained

TR12H4-> Only upper case and numbers plus characters allowed. 6 chars long

Use [A-Z0-9]{6}, this means use letters from A to Z but also all digits 6 times

030-> only numbers. 3 chars long

Find 3 digits one after the other : \d{3}

485-> Only numbers. 3 chars long

Same as above : \d{3}

Should be like XXXXXX-XXX-XXX with minus

Now use them together : [A-Z0-9]{6}-\d{3}-\d{3}

CodePudding user response:

Basically you want groups of uppercase letters and numbers separated by hyphens.

You might use

[A-Z0-9] (-[A-Z0-9] )*

Reguar expressions usually are bad at counting. AFAIK this one would not work on all engines but implements the limitation of up to six characters per group:

[A-Z0-9]{1,6}(-[A-Z0-9]{1,6})*

Edit: With the additional information given now, further restrictions apply. So the regex would look like

[A-Z0-9]{6}-\d{3}-\d{3}
  •  Tags:  
  • Related