I have implemented this regex for matching a string for validation purposes:
^(?<serialCode>[a-zA-Z0-9]{0,3})(?:(?<serialMarket>[a-zA-Z]{1,2})(?<serialSuffix>(?<=^.{5})[a-zA-Z0-9]*)?)?
I'm using it in JS using match()
function like this:
const regex = '^(?<serialCode>[a-zA-Z0-9]{0,3})(?:(?<serialMarket>[a-zA-Z]{1,2})(?<serialSuffix>(?<=^.{5})[a-zA-Z0-9]*)?)?';
const stringToMatch = 'EV1FOO12FF344';
const result = stringToMatch.match(new RegExp(regex));
console.log(result); // returns each group for match and also the full match
What basically this does is that it's doing the following step by step validations and creating groups:
- first 3 characters should be only alphanumeric characters
- characters 4 and 5 should be only letters
- all the rest of the characters should be alphanumeric characters
This validation is done for every typed value in an input field, character by character.
Using lookbehind as you can see above, this works perfectly for my purposes in Chrome and Mozilla Firefox browsers.
The problem: lookbehind
(in current case (?<=^.{5})
) is not supported on Safari browser as per this link: https://caniuse.com/js-regexp-lookbehind We receive this error in this case: Invalid regular expression: invalid group specifier name
Is there any alternative to that lookbehind so the regex will work in the exact same way?
I have the link where I tested some values for exemplification: https://regex101.com/r/fPmiTk/1
There you can see how the strings are matched and how the groups are created.