1
votes

Trying to build regex for string (company/organisation name) with below conditions:

  • no leading or trailing space
  • no double space in between
  • shouldn't allow only single character (alphanumeric or white listed)
  • can start with alphanumeric or white listed character
  • shouldn't allow any white listed character entered multiple times

regex for these: /(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_')); // shouldn't allow

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('a')); // shouldn't allow

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc   abc')); // shouldn't allow

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('_123')); // works fine

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('# abc')); // works fine

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc!')); // works fine

console.log(/(?! )([a-zA-Z0-9_\.\-#&])+([a-zA-Z0-9_\.\-#&\s])*(?<! )$/.test('abc abc# abc')); // works fine

current regex doesn't match all the criteria and couldn't figure out what's the problem with regex ?

1
Try /^[a-zA-Z0-9_.#&-]+(?:\s[a-zA-Z0-9_.#&-]+)*$/Wiktor Stribiżew
@WiktorStribiżew this regex allows single character. /^[a-zA-Z0-9_.#&-]+(?: [a-zA-Z0-9_.#&-]+)*$/.test('#') this should return false but it returns true.Valay
@Valay what's a "white listed character"?zer00ne
I see your expected match also has !, but your regex does not have it. I added ! to the character class in my answer. You may add more chars there, but mind - must stay at the end of the character class, right before ].Wiktor Stribiżew
@georg valid point. that shouldn't be allowed. updating requirements. thanks.Valay

1 Answers

2
votes

You may use

/^(?=.{2})(?!(?:[^_.#&!-]*[_.#&!-]){2})[a-zA-Z0-9_.#&!-]+(?:\s[a-zA-Z0-9_.#&!-]+)*$/

Details

  • ^ - start of string
  • (?=.{2}) - any 2 chars must be at the start
  • (?!(?:[^_.#&!-]*[_.#&!-]){2}) - no 2 occurrences of _.#&!- chars in the string
  • [a-zA-Z0-9_.#&-]+ - 1 or more allowed chars (other than whitespace)
  • (?:\s[a-zA-Z0-9_.#&!-]+)* - 0+ occurrences of
    • \s - 1 whitespace
    • [a-zA-Z0-9_.#&!-]+ - 1+ letters, digits and some symbols
  • $ - end of string.

JS demo

var rx = /^(?=.{2})(?!(?:[^_.#&!-]*[_.#&!-]){2})[a-zA-Z0-9_.#&!-]+(?:\s[a-zA-Z0-9_.#&!-]+)*$/;
console.log(rx.test('_')); // shouldn't allow
console.log(rx.test('a')); // shouldn't allow
console.log(rx.test('abc   abc')); // shouldn't allow
console.log(rx.test('_123')); // works fine
console.log(rx.test('# abc')); // works fine
console.log(rx.test('abc abc!')); // works fine
console.log(rx.test('abc abc# abc')); // works fine