11
votes

Building an expression that will reject an untrimmed input string.

Have a group of white-listed symbols, including whitespace. But it cannot be used at the first or at the last one position. However, it may be used between any leading and trimming white-listed symbol in any amount.

Have a following expression:

^[^\s][A-Za-z0-9\s]*[^\s]$

... but it doesn't work in several reasons, at least it still matches at leading and trailing position any non-whitespace symbol even if it's not white-listed. Futhermore, it won't match single letter word even if it matches to the expression.

The whitelist is A-Z, a-z, 0-9, whitespace.

Valid case:

Abc132 3sdfas // everything ok

Invalid case #1:

 asd dsadas // leading\trailing space is exist

Invalid case #2:

$das dsfds // not whitelisted symbol at the leading\trailing position

So, how to add a whitespace symbol to the white-list if it isn't the leading or the trailing symbol?

2
Could you make some examples of both valid and invalid cases? - Masked Man
try using \\s please let me know if that helped, I had same issue and it was what i was missing - kolboc
@MaskedMan, yeah, take a look - WildDev
^[A-Za-z0-9]+(?:\s+[A-Za-z0-9]+)*$ - ridgerunner
^[A-Za-z0-9]+.*[A-Za-z0-9]+$: first character should be alphanumeric and at least has one occurrence, and the last also should be the same, with everything in between. Does it solve the problem? - Masked Man

2 Answers

15
votes

You could use lookarounds to ensure that there are no spaces at both ends:

^(?! )[A-Za-z0-9 ]*(?<! )$

Live demo

But if the environment doesn't support lookarounds the following regex works in most engines:

^[A-Za-z0-9]+(?: +[A-Za-z0-9]+)*$
2
votes

depending on your regex engine supporting look around

^(?=[A-Za-z0-9])([A-Za-z0-9\s]*)(?<=[A-Za-z0-9])$

Demo