praks5432
praks5432

Reputation: 7792

What does this regex for @mentions do?

So I've been trying to figure out what this regex mean - and I'm not getting very far.

(\w+\.?(?:\w+)?)

The language is Javascript.

I understand parts of this regex - it looks like it's capturing dots, any word, but forbidding word.word - but I'm not sure?

Upvotes: 0

Views: 70

Answers (2)

p.s.w.g
p.s.w.g

Reputation: 149020

It's not forbidding word.word. The (?:…) creates a non-capturing group. It's just like a regular (…) group, but it is not extracted in a separate capture in the result.

So, this is equivalent to (\w+\.?(\w+)?), except that it only has 1 capture group.

Upvotes: 2

Dan Tao
Dan Tao

Reputation: 128307

It's matching a word (letters, numbers, underscore), optionally followed by a dot, optionally followed by another word. Like:

"foo"
"foo."
"foo.bar"

Breakdown:

  • \w+ a word (as you already knew)
  • \.? an optional dot. The ? means "match zero or one of these"
  • (?:\w+)? an optional word. The ?: at the beginning means "don't capture this" (as opposed to the parens enclosing the whole thing, which mean "do capture this); and the ? at the end means, again, that it's optional

Upvotes: 1

Related Questions