Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

regex

ruby

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?

like image 918
user984621 Avatar asked Dec 05 '22 16:12

user984621


2 Answers

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 +.

like image 59
Andrew Clark Avatar answered Feb 15 '23 22:02

Andrew Clark


/\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

like image 41
Seamus Abshere Avatar answered Feb 15 '23 23:02

Seamus Abshere