I wanted to design an regex for not allowing whitespace at the beginning and at the end of a string, but allows all special characters , spaces , lowercase and uppercase alphabets and numbers in between
The regex I tried is :
'^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$'
I am using it as a pattern validator inside input in angular as : pattern ="^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$'"
anyhelp would be greatly appreciated
CodePudding user response:
You need either
Validators.pattern('\\S(?:.*\\S)?')
Or
Validators.pattern(/^\S(?:.*\S)?$/)
In both cases, the regex is ^\S(?:.*\S)?$
and matches
^
- start of string\S
- any char other than whitespace(?:.*\S)?
- an optional occurrence of any zero or more chars other than line break chars as many as possible and then a non-whitespace char$
- end of string.
CodePudding user response:
All the ASCII alphabets and special characters are defined with [!-\[\]-~]
By making sure the first and optional last is this class is all that's needed.
^[!-\[\]-~] (?:[^\S\r\n]*[!-\[\]-~])*$
https://regex101.com/r/JpsOvy/1
^
[!-\[\]-~]
(?: [^\S\r\n]* [!-\[\]-~] )*
$
[^\S\r\n]
is just non-linefeed white space. Replace with \s
if needed.