0

How can I create regex rule for name in Track1, following these rules:

  • Allowed Characters would be: ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789 .()-$
  • Not Allowed Characters would be: ^!"&'*+,:;<=>@_[]#%?
  • Required character - only must character / appear
  • The max size is 26 characters , min size 2.

I tried:

\^[^\^!"&'*+,:;<=>@_\[\]\\#%?]{2,26}\^ Result FAIL: removing "/" will pass pattern 
\^([-.()0-9a-zA-Z]*\/[-.()\w\s\/]*){1,26}\^ Result FAIL: more than 26 characters will pass pattern
^[-.()\w\s\/]{2,26}\^ Result FAIL: removing "/" will pass pattern

Sample of Name in Track1:

  • ^TEST/TEST^- Should Pass
  • ^TEST TEST^- Should Fail
  • ^TEST/TE/ST^ - Should Fail
  • ^TEST/TE+ST^ - Should Fail

Thanks!

Poul Bak
  • 10,450
  • 5
  • 32
  • 57
CodingMerc
  • 41
  • 5
  • Why do you need to do this with a regular expression? Validating the total length of the field would be challenging while also ensuring presence of a single character. Much simpler to do with a programming language of some sort. – miken32 Jul 14 '22 at 23:08
  • I can do that of course. I thought it would be better to create one regex rule handling it. – CodingMerc Jul 15 '22 at 05:53
  • Well, come back to your 1000 character regex in a year and see if it makes sense to you. Shorter != better. – miken32 Jul 15 '22 at 14:18

1 Answers1

1

If there has to be at least ^ at the start and end, and there has to be at least a single / then the minimum amount of characters would be 3 instead of 2.

In that case, you might use:

\^(?=[A-Z .()\/-]{1,24}\^)[A-Z .()-]*\/[A-Z .()-]*\^

Explanation

  • \^ Match ^
  • (?=[A-Z .()\/-]{1,24}\^) Positive lookahead, assert 1,24 of the allowed chars followed by ^ to the right to make a total of 2-26 characters
  • [A-Z .()-]*\/[A-Z .()-]* Match / between optional allowed chars
  • \^ Match ^

See a regex demo.

If the / can not be at the start or at the end (matching at least 5 characters in that case)

\^(?=[A-Z .()\/-]{1,24}\^)[A-Z .()-]+\/[A-Z .()-]+\^

See another regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70