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?
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 +
.
/\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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With