javascript - Regex to match only when expression match is no more than 12 characters long -


i trying create regular expression (java/javascript) matches following regex, when there fewer 13 characters total (and minimum of 4).

(cot|med)[abcd]?-?[0-9]{1,4}(([jk]+[0-9]*)|(\ ddd)?)   ← originally posted

(cot|med)[abcd]?-?[0-9]{1,4}(([jk]+[0-9]*)|(\ [a-z]+)?) 

these values should (and do) match:

med-123 cota-1224 med4 cotb-892k777 med-33 ddd med-234j5678 

this value matches, don't want (i want match if there fewer 12 characters total):

cot-1111j11111111111111 

see http://regexr.com/3bs7b http://regexr.com/3bsfv

i have tried grouping expression , putting {4,12} @ end, makes 4 12 instances of whole expression matching.

i feel missing simple...thanks in advance help!

the answer looking is

(?!\s{13})(?:cot|med)[abcd]?-?\d{1,4}(?:[jk]+\d*|(?: [a-z]+)?) 

see regex demo

note impossible check length of phrase not whole string or has spaces inside since boundaries bit "blurred". thus, (?!\s{13}) kind of workaround makes sure not have string without whitespace 13 characters long or longer.

the regex breakdown:

  • (?!\s{13}) - check if substring follows not consist of 13 non-whitespace characters
  • (?:cot|med) - of values in alternation (cotormed`)
  • [abcd]?-? - optional a, b, c, d , optional -
  • \d{1,4} - 1 4 digits
  • (?:[jk]+\d*|(?: [a-z]+)?) - group of 2 alternatives:
    • [jk]+\d* - j or k, 1 or more times, , 0 or more digits
    • (?: [a-z]+)? - optional space , 1 or more latin uppercase letters

Comments