8

So, I've been trying to write out a regular expression for something like a resistance value, which contains a certain amount of digits and at most one letter, but is always a certain amount of characters total (let's use the example of a four-character resistance code).

First I could do '\d*[RKM]\d*' but that would allow something like 'R'.

Also, I could do something like '[\dRKM]{4}', but this will allow things like 'RRR4' which is not a value that I would want.

'\d{1,4}[Rr]\d{0,3} | ([RKM]\d{3}) | (\d{4})', though more specific, would still allow '1234R567' which is not four characters.

So basically, is there a more compact way of writing '[RKM]\d\d\d | \d[RKM]\d\d | \d\d[RKM]\d | \d\d\d[RKM] | \d\d\d\d'?

Marcus Gladir
  • 403
  • 1
  • 8
  • 13
  • 3
    I'm not sure if you would like doing it, but maybe the best way of checking length would be using the surrounding programming language. Our company has a list of "validation types" in an XML file, and as well as a regex on each, it lets you set a min/max length. (In this case, just set both to 4) – Katana314 Jul 17 '13 at 13:23
  • 1
    `^[RKM]\d{3}|\d[RKM]\d{2}|\d{2}[RKM]\d|\d{3}[RKM]|\d{4}$` is too complex? Or, if you're looking within other text: `\b(?:[RKM]\d{3}|\d[RKM]\d{2}|\d{2}[RKM]\d|\d{3}[RKM]|\d{4})\b` – Brad Christie Jul 17 '13 at 13:25

1 Answers1

9

Depending on your regex flavor, you can use a lookahead:

^(?!(?:\d*\D){2})[\dRKM]{4}$
  • (?!(?:\d*\D) - Assert that there aren't two non-digit characters.

Or:

^(?=.{4}$)\d*(?:[RKM]\d*)?$
  • (?=.{4}$) - Assert that the length of the string is 4.

See also: Regular Expressions: Is there an AND operator?

Community
  • 1
  • 1
Kobi
  • 135,331
  • 41
  • 252
  • 292