user984621
user984621

Reputation: 48521

How to allow string with letters, numbers, period, hyphen, and underscore?

I am trying to make a regular expression, that allow to create string with the small and big letters + numbers - a-zA-z0-9 and also with the chars: .-_

How do I make such a regex?

Upvotes: 4

Views: 12264

Answers (2)

Seamus Abshere
Seamus Abshere

Reputation: 8526

/\A[\w\-\.]+\z/

  • \w means alphanumeric (case-insensitive) and "_"
  • \- means dash
  • \. means period
  • \A means beginning (even "stronger" than ^)
  • \z means end (even "stronger" than $)

for example:

>> 'a-zA-z0-9._' =~ /\A[\w\-\.]+\z/
=> 0 # this means a match

UPDATED thanks phrogz for improvement

Upvotes: 4

Andrew Clark
Andrew Clark

Reputation: 208725

The following regex should be what you are looking for (explanation below):

\A[-\w.]*\z

The following character class should match only the characters that you want to allow:

[-a-zA-z0-9_.]

You could shorten this to the following since \w is equivalent to [a-zA-z0-9_]:

[-\w.]

Note that to include a literal - in your character class, it needs to be first character because otherwise it will be interpreted as a range (for example [a-d] is equivalent to [abcd]). The other option is to escape it with a backslash.

Normally . means any character except newlines, and you would need to escape it to match a literal period, but this isn't necessary inside of character classes.

The \A and \z are anchors to the beginning and end of the string, otherwise you would match strings that contain any of the allowed characters, instead of strings that contain only the allowed characters.

The * means zero or more characters, if you want it to require one or more characters change the * to a +.

Upvotes: 12

Related Questions