Home > OS >  Difficulty forming a regular expression
Difficulty forming a regular expression

Time:03-05

I'm trying to check a string to make sure that it only contains lowercase and uppercased letters, the digits 0-9, underscores, dashes and periods.

The regular expression I've been using for letter, numbers, underscores and dashes works fine and is this:

"[^a-zA-Z0-9_-]"

I'm having difficulty adding the check for spaces and periods though.

I've tried:

"[^a-zA-Z0-9_- ]" (added a space after the dash) "[^a-zA-Z0-9_-\s\.]" (trying to escape a white space character)

I've also tried putting the \s and \. outside of the main block and also in blocks of their own.

Thanks for any advice.

CodePudding user response:

A hyphen (representing the character) must be at the beginning or at the end of the (negating) character class.

Inside a character class the period is a normal character, it doesn't need to be escaped.

let pattern = "[^a-zA-Z0-9_. -] "

CodePudding user response:

Be careful about adding characters which have a special meaning: you forgot the hyphen. I think that this is what you are looking for:

"[\^ a-zA-Z0-9_,\.\-]"
  • Related