1

In the following text what Regex (Javascript) would match "user" (user is a random name), excluding the "@" character?

I want to tag this @user here
and this @user
@user


I have looked at the following solutions and made the following regexes that did not work

RegEx pattern to match a string between two characters, but exclude the characters

\@(.*)\s

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

(?!\@)(.*?)(?=\s)

Regex: Matching a character and excluding it from the results?

^@[^\s]+

Finally I made this regex that works but returns "@user" instead of "user":

@[^\s\n]+

The Javascript used to execute the regex is:

string.match(/@[^\s\n]+/)
Community
  • 1
  • 1
Dokinoki
  • 171
  • 2
  • 10
  • 1
    How are you calling the regex? That's what looks like the problem. – Shlomo Nov 09 '15 at 21:41
  • 1
    It seems like at least partially, the problem is not strictly the regex but also how you are using it in code. The last expression you mention should be fine in order to match the username but not to extract it. To extract it you need to form a capture group with parenthesis, such as `@([^\s\n]+)`. – mah Nov 09 '15 at 21:41
  • Post your exact JavaScript. – PM 77-1 Nov 09 '15 at 21:42

2 Answers2

2

I see I need to post a clarification.

If one knows a pattern beforehand in JS, i.e. if you do not build a regex from separate variables, one should be using a RegExp literal notation (e.g. /<pattern>/<flag(s)>).

In this case, you need a capturing group to get a submatch from a match that will start with a @ and go on until the next non-whitespace character. You cannot use String#match if you have multiple values inside one input string, as global regexps with that method lose the captured texts. You need to use RegExp#exec:

var s = "I want to tag this @user here\nand this @user\n@user";
var arr = [];
var re = /@(\S+)\b/g;
while ((m=re.exec(s)) !== null) {
  arr.push(m[1]);  
}
document.write(JSON.stringify(arr));

The regex I suggest is @(\S+)\b:

  • @ - matches a literal @
  • (\S+) - matches and captures into Group 1 one or more non-whitespace characters that finish with
  • \b - word boundary (remove if you have Unicode letters inside the names).
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
0

If you execute it this way, it should work:

var str = "I want to tag this @user here";
var patt = new RegExp("@([^\\s\\n]+)");
var result = patt.exec(str)[1];
Shlomo
  • 14,102
  • 3
  • 28
  • 43
  • 1
    This answer is wrong. The output is `u`. You need to be careful with the ``\`` inside RegExp constructor notation. – Wiktor Stribiżew Nov 09 '15 at 22:09
  • Come on, it is not even probably. When one knows the pattern at design time, a literal notation should be used, it is less error prone. There are tons of such questions on SO asking why single slashes do not work. Use `var patt = /@(\S+)/;`. – Wiktor Stribiżew Nov 09 '15 at 22:18