Defining a regex for two characters then two numbers

I am using a regex in my React app to validate the input of the form entry. The input uses an onChange listener to call a function which sets the state on character change.

A valid input is two characters followed by two digits. i.e RD01 or EX12

I have it plumbed up with the re working. It matches for the correct case although it also works for just two digits. i.e. 01 or 12

    const onAssetChange = (e) => {
        const input = e.target.value.toUpperCase()
        const re = new RegExp('^[A-Z]{0,2}[0-9]{0,2}$')
        if (!input || input.match(re)) {
            setAssetID(input)
        }
    }

The regex needs to be able to update on each key stroke as it updates state on each change event.

RegExp('^[A-Z]{0,2}[0-9]{0,2}$') will check for either 0,1 or 2 characters. The same would do for the numbers so even A1 would be a valid one. Try the following:

const re = new RegExp('^[A-Z]{2}[0-9]{2}$')

A regex usually comes within this form / abc /, where the search pattern is delimited by two slash characters /. At the end we can specify a flag with these values (we can also combine them each

You could use '^[A-Z][A-Z][0-9][0-9]$'.

Regular expressions come in handy for all varieties of text processing, but are often misunderstood--even by veteran developers. Here's a look at intermediate-level regular expressions and what

This should work...

const onAssetChange = (e) => {
    const input = e.target.value.toUpperCase()
    const re = new RegExp('^\w{2}\d{2}$')
    if (!input || input.match(re)) {
        setAssetID(input)
    }
}

Consecutive Repeating Characters Regex Matches any character except new line (). [bc-] The characters b, c or - (dash). A ' character followed by any single character which is neither ' nor a newline.

Okay, so it isn't pretty...

    const onAssetChange = (e) => {
        const input = e.target.value.toUpperCase()
        const re = new RegExp('^[A-Z]{0,2}[0-9]{0,2}$')
        if (!input || input.match(re) && (input.length < 2 ? input[0].match(/[A-Z]/) : input.slice(0,2).match(/[A-Z][A-Z]/)) ) {
            setAssetID(input)
        }
    }

but it works. If anyone has a more elegant solution I'm interested to hear it.

If we are matching phone numbers for example, we don't want to validate the letters "(abc) def-ghij" as being a valid number! There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

Try using [A-Z]{2}[0-9]{2} regex.

The mistake in your regex was {0,2} quantifier matches for 0 to 2 elements in the provided charset. Use {2} instead. This will assert to check for exactly 2 count of charset.

What my suggestion is to use a mockFunction to update your input to tme required standard like mapping HI as HI00, AA as AA00, Aa as Aa00 etc and test this mocked string. This is a sample for the same.

console.log('R -- ', mockInput('R'));
console.log('RD --', mockInput('RD'));
console.log('RD0 -- ', mockInput('RD0'));
console.log('RD01 -- ', mockInput('RD01'));
console.log('01 -- ', mockInput('01'));
console.log('R01 -- ', mockInput('R01'));
console.log('RD011 -- ', mockInput('RD011'));

function mockInput(input) {
  const returnStr = "AA00";
  const fakeInput = input.length >= 4? input: input + returnStr.substring(input.length, 4);
  const re = RegExp(/[A-Z]{2}[0-9]{2}/);
  let status = false;
  if (re.test(fakeInput)) {
    status = true;
  }
  return status;
};

To match all characters from 0 to 255, we’ll need a regex that matches between one and three characters. The regex [0-9] matches single-digit numbers 0 to 9. [1-9] [0-9] matches double-digit numbers 10 to 99. That’s the easy part. Matching the three-digit numbers is a little more complicated, since we need to exclude numbers 256 through 999.

The word boundary \b matches positions where one side is a word character (usually a letter, digit or underscore—but see below for variations across engines) and the other side is not a word character (for instance, it may be the beginning of the string or a space character). The regex \bcat\b would therefore match cat in a black cat, but it

The next two columns work hand in hand: the "Example" column gives a valid regular expression that uses the element, and the "Sample Match" column presents a text string that could be matched by the regular expression.

Examples related to use of a combination of alphabets letters and numbers¶. Restrict one character which matches between a to z or A to Z or 0 to 9 or _ (i.e. match one character from [a-zA-Z0-9_]): regex(., ‘^\w$’)

Comments
  • What is the question?
  • The quantifers should be {2} to match 2 times. {0,2} Matches 0, 1 or 2 times.
  • "The regex needs to be able to update on each key string as it updates state on each change." - If the intermediate result aren't also valid like the end result, you need a different regex check for your end result. I'd recommend checking only the end result and providing an example in a tooltip, watermark or something.
  • @Croc Please see my updated answer
  • I missed an importand piece of information which I have added to the question. It needs to be able to be updated per key stroke. In this case, only works if the whole case is added then submitted.
  • Could you please clarify the requirement with an example?
  • R = valid RD = valid RD0 = valid RD01 = valid 01 = invalid R01 = invalid RD011 = invalid
  • @Croc I need to check whether this could be achieved with simple regex.
  • @Croc Please see my updated answer