Home > Mobile >  Regex to validate characters and numbers concatenated with -
Regex to validate characters and numbers concatenated with -

Time:12-22

I'm trying to match a string that Characters and numbers cannot be concatenated, if you want to concatenate use a hyphen.

For example, these should all match:

  • abc-123-123-***
  • 123-abc-abc-***
  • 123-abc-123-***
  • abc-123-abc-***
  • abc-efg-***

not match:

  • abc123
  • 123abc
  • abc1
  • a1b2 Please help me to find a javascript regex.

Please help me to find a javascript regex.

CodePudding user response:

My regex is quite complex :

^([^\d\-] |\d )(\-([^\d\-] |\d ))*$

Test string is matched or not in javascript:

/^([^\d\-] |\d )(\-([^\d\-] |\d ))*$/gi.test('abc-123-123-***')

CodePudding user response:

Simply test for transition from alpha to digit, or digit to alpha, and take the logical opposite of that:

[
  'abc-123-123-***',
  '123-abc-abc-***',
  '123-abc-123-***',
  'abc-123-abc-***',
  'abc-efg-***',
  'abc123',
  '123abc',
  'abc1',
  'a1b2',
].forEach(str => {
  var ok = !/\d[a-z]|[a-z]\d/.test(str);
  console.log(str, ' ==> ', ok);
});

  • Related