Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex - match a string without leading and trailing spaces

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?

like image 509
WildDev Avatar asked Aug 13 '16 15:08

WildDev


People also ask

What does %s mean in regex?

The Difference Between \s and \s+ For example, expression X+ matches one or more X characters. Therefore, the regular expression \s matches a single whitespace character, while \s+ will match one or more whitespace characters.

What does \\ mean in regex?

\\. matches the literal character . . the first backslash is interpreted as an escape character by the Emacs string reader, which combined with the second backslash, inserts a literal backslash character into the string being read. the regular expression engine receives the string \.

Which function of the string will remove leading and trailing spaces?

The STRIP function is similar to the TRIM function. It removes both the leading and trailing spaces from a character string.

Does \w include spaces regex?

\W means "non-word characters", the inverse of \w , so it will match spaces as well.


2 Answers

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]+)*$
like image 110
revo Avatar answered Oct 14 '22 20:10

revo


depending on your regex engine supporting look around

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

Demo

like image 24
alpha bravo Avatar answered Oct 14 '22 19:10

alpha bravo