Regular expression to match IRC nickname

人走茶凉 提交于 2019-12-04 13:45:34

问题


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


回答1:


# 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 


来源:https://stackoverflow.com/questions/5163255/regular-expression-to-match-irc-nickname

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!