Мастер-классы по Javascript Екатеринбург Ростов-на-Дону Москва Узнать больше...
Содержание (скрыть) Содержание (показать)

Test a clanned nick

Create a regexp to validate a nick. A nick consists of a clan and a name:

"[Clan]John", "{CLAN}John", "(Clan)John"

A clan is either in square or curly or round brackets, brackets must be same on both sides. The clan and the name have no spaces:

"[Clan)john" // invalid, different brackets
"[My Clan]john galt"  // clan is invalid, name is invalid (spaces)

The call str.match(your regexp) must return null for invalid nicks and an array for valid ones.

P.S. Can the array contain the clan Clan and the name John?

Решение
Решение

First, we need to match a clan name. Unfortunately, there is no way to tell the regexp engine that «if the opening bracket is '[', then the closing should be ']'».

So we have to match all three types of clan names. A clan name is something non-spacy \S+, so there are 3 alternatives for each type of brackets: \[\S+] | \{\S+} | \(\S+\)

Alternatives should be grouped together: (..|..|..). It is required, because we add the next item after them: a name \S+.
It gives us: (\[\S+] | \{\S+} | \(\S+\))\S+

Finally, the pattern should test the whole string, so it starts with '^' and ends with '$': ^(\[\S+] | \{\S+} | \(\S+\))\S+$

(By the way, as you can see most special characters don’t need to be escaped)

In action:

var str = "[Clan]John"

var re = /^(\[\S+]|\{\S+}|\(\S+\))\S+$/
alert( str.match(re) ) // can also re.test

P.S. Now let’s see how to capture the clan. The regexp above actually does that, but the clan alternatives are in a group. But it comes in brackets, like {Clan}.

Of course we’d like to have it without brackets. So, let’s wrap each clan \S+ into brackets (\S+): ^(\[(\S+)] | \{(\S+)} | \((\S+)\))\S+$

The inconvenience is that depending on which bracket matches, the corresponding array item is set. The external code should take care of it.

For example:

var re = /^(\[(\S+)]|\{(\S+)}|\((\S+)\))\S+$/

"[Clan]John".match(re) 
// ["[Clan]John", "[Clan]", *!*"Clan"*/!*, undefined, undefined]

"{Clan}John".match(re) 
// ["[Clan]John", "{Clan}", undefined, *!*"Clan"*/!*, undefined]

"(Clan)John".match(re) 
// ["(Clan)John", "(Clan)", undefined, undefined, *!*"Clan"*/!*]

#290
Наверх

Реклама

Нашли опечатку?

Нашли опечатку на сайте? Что-то кажется странным?
Выделите соответствующий текст и нажмите Ctrl+Enter!

Последние Комментарии

Помоги другим!

Помоги другим узнать о хорошей статье!