Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match IRC nickname

Tags:

regex

irc

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: < - [ ] \ ^ { }

like image 835
Mark Szymanski Avatar asked Mar 02 '11 04:03

Mark Szymanski


People also ask

How to match in regular expression?

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

What is\\ w in regex?

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/

What is the regular expression for characters?

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.


1 Answers

# 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 
like image 165
Phrogz Avatar answered Sep 22 '22 00:09

Phrogz