How would I use a regular expression to match an IRC nickname? This is being done in Ruby if that makes a difference (it probably will, with the syntax of the regex, but who knows.)
EDIT: An IRC nickname can contain any letter, number, or any of the following characters: <
- [ ] \
^ { }
To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).
The RegExp \W Metacharacter in JavaScript is used to find the non word character i.e. characters which are not from a to z, A to Z, 0 to 9. It is same as [^a-zA-Z0-9]. Syntax: /\W/
A regular expression (shortened as regex or regexp; sometimes referred to as rational expression) is a sequence of characters that specifies a search pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation.
# If you are testing a single string
irc_nick_re = /\A[a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*\z/i
# If you are scanning them out of a larger string
irc_nick_re = /(?<=[^a-z_\-\[\]\\^{}|`])[a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]*/i
The above allows single-character names. If two characters are required, change the *
to +
. If three characters (or more) are required, change it to {2,}
, where '2' is the minimum number of characters minus 1.
If there is a maximum number of characters (for example, EFNet only allows nicknames up to 9 characters lone, while Freenode allows nicks up to 16 characters long) then you can include that number (minus 1) after the comma. For example:
# Validate nicknames that are between 3 and 16 characters long (inclusive)
irc_nick_re = /\A[a-z_\-\[\]\\^{}|`][a-z0-9_\-\[\]\\^{}|`]{2,15}\z/i
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