RegEx - remove leading and trailing spaces when content matches
I want to try and build a RegEx statement that will remove any pre-differentiated or trailing spaces from the string (but don't leave those contained in the string intact), as well as those that match the selected format. For example, a string must be no more than 20 characters, can contain any characters from a-zA-Z0-9, as well as underscores and hyphens. But most importantly, it should trim or ignore any whitespace found at the beginning or end of the line, like so:
Correct: "Have a nice day"
Wrong: "Have a nice day"
I have tried many different ways to do this, but unfortunately so far I have not been able to find a formula that does exactly what I want. Can anyone help me with a suitable RegEx? (this is RegEx in its simplest form, not platform specific).
source to share
This should suit your needs:
^\S[\w\s-]{0,18}\S$
18
are maxlength - 2
strings, because of the two \S
, which will match any non-whitespace char. For example, in this case, the strings will not match if their length is higher than 20
. Moreover, strings will not match if their length is less than 2
characters, due to the same above restriction.
source to share