Home > Software engineering >  numbers cannot follow characters
numbers cannot follow characters

Time:12-16

I'm trying to match a string that numbers cannot follow characters

For example, these should all match:

  • abc-123
  • 123-abc
  • 123-abc-123
  • abc-123-abc

not match:

  • abc123
  • 123abc
  • abc1
  • a1b2

Please help me to find a javascript regex.

CodePudding user response:

To match strings that contain only letters separated by numbers, you can use the following regular expression:

/^[a-zA-Z] (?:-[a-zA-Z] )*$/

This regular expression will match strings that start and end with letters, and have a number in between. The letters and the number must be separated by a hyphen.

For example, you can use the following code to test this regular expression:

const regex = /^[a-zA-Z] (?:-[a-zA-Z] )*$/;

console.log(regex.test("abc-123")); // should return true
console.log(regex.test("123-abc")); // should return true
console.log(regex.test("123-abc-123")); // should return true
console.log(regex.test("abc-123-abc")); // should return true
console.log(regex.test("abc123")); // should return false
console.log(regex.test("123abc")); // should return false
console.log(regex.test("abc1")); // should return false
console.log(regex.test("a1b2")); // should return false

This code defines a regular expression using the pattern described above, and then uses the test method to check if various strings match the pattern. The test method returns a boolean indicating whether the string matches the pattern or not.

Edited, since the question changed (I am still not sure if it is correct).

CodePudding user response:

Assuming the following requirements:

  • alternating between letters and digits separated by hyphen
  • must not start or end with a hyphen, e.g.: abc-123- not valid
  • if no hyphen, either only letters or digits: abc or 123 are valid

By matching the sequence and making everything optional.   > regex101 demo

^\b\d*(?:\b-?[a-z] -\d )*-?\b[a-z]*$

Or by use of lookaheads to disallow \d-\d or [a-z]-[a-z].   > regex101 demo

^(?:\d -?\b(?!\d)|[a-z] -?\b(?![a-z])) $

In both variants the optional hyphen is required between due the word boundary.

  • Related