Home > Back-end >  REGEX : accept only alphanumeric characters and spaces except the spaces at the begining or ending o
REGEX : accept only alphanumeric characters and spaces except the spaces at the begining or ending o

Time:05-21

I need to implement regular expression that accept only alphanumeric characters and spaces except the spaces at the begining or ending of expression.

'   aaaa978aa' ===> fail
'aaaaaa      ' ===> fail
'aaaaaaaaAAAa' ===> match
'aaaaaaa  aaa' ===> match
'68776  67576' ===> match
'aAAAa756Gaaa' ===> match

CodePudding user response:

I would write the regex as the following in case insensitive mode:

^[a-z0-9](?:[a-z0-9 ]*[a-z0-9])?$

This requires a leading alphanumeric character, along with optional alphas or spaces in the middle, ending also with an alphanumeric character, at least for the case where the length be 2 or more characters.

Sample code:

var inputs = ["   aaaa978aa", "aaaaaa      ", "aaaaaaaaAAAa", "aaaaaaa  aaa", "68776  67576", "aAAAa756Gaaa"];
inputs.forEach(x => console.log(x   (/^[a-z0-9](?:[a-z0-9 ]*[a-z0-9])?$/i.test(x) ? " : match" : " : fail")));

CodePudding user response:

Try this:

^\w (?:[ \t] )?\w $

^ : Asserts position at start of a line

\w : Matches any word character (equivalent to [a-zA-Z0-9_]), between one and unlimited times.

(?:[ \t] )? : Non capturing group, matches the spaces and tab, ? ensures to match the previous token between 0 and 1 time.

$: Asserts position at end of a line

https://regex101.com/r/sMcYuq/1

  • Related