Trying to build regex for string (company/organisation name) with below conditions:
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 ?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.