Home > Mobile >  Regular expression that checks for name special char and number all at once
Regular expression that checks for name special char and number all at once

Time:09-15

I've got a system where a user can enter a code followed by a comma, quantity and finally a new line.

This is in a textarea that passes the value to state onChange so I've currently got it setup to split the string on \n which is working perfectly.

My problem is that my regex to check each order line isnt working. For example if a user enters:

11-11,12 (this is product code,qty) my regex is failing, heres an example.

const re = /^[a-zA-Z0-9\-\\/. ][,][0-9]$/;
i = '11.11,12'
console.log(i.match(re))

To me this reads as a start, group for the code, group for the comma, group for the qty, clearly I've got something wrong as null keeps getting logged out.

Any help would be appreciated.

CodePudding user response:

[] are character classes.

() are group delimiters.

You're probably looking for this:

const re = /^([a-zA-Z0-9\-\\/. ] )(,)([0-9] )$/;
i = '11.11,12'
console.log(i.match(re))

Now, to make your regex a little more efficient, you probably don't care about the actual comma, and you don't have to specify 0-9:

const re = /^([a-zA-Z\d\-\\/. ] ),(\d )$/;
i = '11.11,12'
console.log(i.match(re))

  • Related