Question

I'm trying to extract (potentially hyphenated) words from a string that have been marked with a '@'.

So for example from the string

var s = '@moo, @baa and @moo-baa are writing an email to a@bc.de'

I would like to return

['@moo', '@baa', '@moo-baa']

To make sure I don't capture the email address, I check that the group is preceded by a white-space character OR the beginning of the line:

s.match(/(^|\s)@(\w+[-\w+]*)/g)

This seems to do the trick, but it also captures the spaces, which I don't want:

["@moo", " @baa", " @moo-baa"]

Silencing the grouping like this

s.match(/(?:^|\s)@(\w+[-\w+]*)/g)

doesn't seem to work, it returns the same result as before. I also tried the opposite, and checked that there's no \w or \S in front of the group, but that also excludes the beginning of the line. I know I could simply trim the spaces off, but I'd really like to get this working with just a single 'match' call.

Anybody have a suggestion what I'm doing wrong? Thanks a lot in advance!!

[edit]

I also just noticed: Why is it returning the '@' symbols as well?! I mean, it's what I want, but why is it doing that? They're outside of the group, aren't they?

Was it helpful?

Solution

As far as I know, the whole match is returned from String.match when using the "g" modifier. Because, with the modifier you are telling the function to match the whole expression instead of creating numbered matches from sub-expressions (groups). A global match does not return groups, instead the groups are the matches themselves.

In your case, the regular expression you were looking for might be this:

'@moo, @baa and @moo-baa are writing an email to a@bc.de'.match(/(?!\b)(@[\w\-]+)/g);

You are looking for every "@" symbol that doesn't follow a word boundary. So there is no need for silent groups.

OTHER TIPS

If you don't want to capture the space, don't put the \s inside of the parentheses. Anything inside the parentheses will be returned as part of the capture group.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top