5

I'm trying to match usernames within a string like:

"user: hi, has anyone seen user today user"

The cases to match:

  • substring is the first word trailing a space, in the middle surrounded by spaces or the last and leading a space
  • Following characters are allowed to trail the word but not returned as a result: ":;,"

The following matches all the cases but returns unwanted spaces and characters (I only want to replace usernames):

/(^(user)[\s|:|;|,])|(\s(user)[\s|:|;|,]?\s)|(\s(user))/gi

In the end I want to replace only username with links.

EDIT: Note that the username can't be matched if it's part of url or other string, except cases when special characters are trailing it.

4 Answers 4

6
+50

Depending upon how transparent you want it to be to users (or what your eventual goal is), you may consider requiring someone to put a symbol (such as @) before a user name, so that they can elect whether or not to have a link to the user...

Aside from that, your expression has several potential errors: character classes (denoted by []) treat nearly all characters literally, including |, the entire alternation syntax makes the third alternation ((\s(user))) into something that will allow matches to userSmith or userJones and not just user - which is something I think you specifically want to disallow...

I think you are asking for something like this:

(^|\s)(user)(?=[:;,\s]|$)

this breaks down to:

(^|\s)      # either assert that this is the beginning, or capture a whitespace character; capture into back-reference #1
(user)      # capture the username 'user' exactly 
(?=         # look-ahead to verify that the following CAN be matched
   [:;,\s]  #    one character that is      :  ;  ,  <or whitespace>
   |        #     -OR-
   $        #    the end of the string
)           # end look-ahead

However, there are a few cases that you might want to consider. By not allowing several types of punctuation after the username, you will exclude results from strings like: Let me know if you see user., have you seen user? or I really like user! - the rejection for URLs should already be accomplished by requiring whitespace (or the beginning of the string) before user - not allowing such punctuation afterwards will reject some cases I think you will want to match. You could simply add in this extra punctuation:

(^|\s)(user\b)(?=[;:,.?!)"\s]|$)

But I would suggest something more like the following (removing the following-punctuation requirement):

(^|\s)(user\b)

I've put all three suggestions on jsFiddle, to show you what you get and allow you to put some of your own strings in.

Which ever way you prefer, these expressions would be used in a find-replace wherein you would replace the whitespace consumed before the user's name with itself in the replace expression:

source.replace(/(^|\s)(user\b)/gi, '$1<a href="/linkToProfile?n=$2">$2</a>')

Though I'm pretty sure I answered the question, please let me know if there are cases you specified that aren't covered!

6

I think you are looking for \b which means "word boundary":

/\buser\b/gi

Edit after your comment:

You can easily add the required characters after your username with a lookahead:

/\buser(?=[:;,\s]|$)/gi

Unfortunately you can't do the same for restrictions on the characters before the username because Javascript doesn't support lookbehinds. But perhaps this is good enough for your needs?

If not, as a workaround you can capture the characters that must occur before the string and replace them with themselves.

2
  • Except that a capture group should be added around user.
    – MetaEd
    Nov 17, 2011 at 22:18
  • This doesn't really work as it also matches false positives like "www.user.com" which isn't desired (this is actually the reason why I'm trying to come up with a new regex)
    – jorilallo
    Nov 17, 2011 at 23:54
3
str.replace(
  /(^|\s)(user)(?=[\s:;,]|$)/gi, // look-ahead credits: Code Jockey
  "$1replacement$3"
);
13
  • I added the dollar at the end of regex, you probably forgot it in the one cited in the question.
    – user1046334
    Nov 22, 2011 at 19:25
  • This seems to work ok, but fails with following strings: "user user user," and "user"
    – jorilallo
    Nov 22, 2011 at 19:47
  • The "user" is your fault (I just took your old regex and changed parentheses, it does not work there as well). Maybe you could change it to /(^|\s)(user)([\s|:|;|,]?\s|$)/gi, I don't know if such thing works. The "user user user" example is harder, since they probably overlap and are not allowed. Run it two times in a chain (first run should do "replacement user replacement", the second run does the middle user. Not that it is elegant but it should do the trick...
    – user1046334
    Nov 22, 2011 at 20:01
  • But I think what you really should do instead of this crazy magic is to use /\buser\b/gi and use a function as a replacement argument to replace where you should programmatically explore the surroundings of the match (you get the position and the whole string in arguments), and there you can simply check if this word is fine to replace or not and return "user" or "replacement" accordingly.
    – user1046334
    Nov 22, 2011 at 20:08
  • I'll mark this as accepted but I still can't get it work: the above one and all the ones I have tried are losing spaces when doing replacement inline. Ideas?
    – jorilallo
    Nov 22, 2011 at 20:10
0
var input = "user: hi, has anyone seen user, today user";
var username = "user";
var rx = new RegExp("(^|\\s)(" + username + ")([\\s:;,]|$)", "gi");

/* 'user: hi, has anyone seen <a href="…">user</a>, today <a href="…">user</a>' */
var result = input.replace(rx, function (match, paren1, username, paren3) {
  return paren1 + '<a href="…">' + username + '<\/a>' + paren3;
});

(^|\s) and (\s|$) instead of \b prevents the leading user: from matching, and works with non-ASCII user names (\b matches any boundary created by characters not matched by [A-Za-z0-9_]; see ECMAScript Edition 5.1, section 15.10.2.6 "Assertion").

You need to escape the username variable value if it contains any RegExp-special characters, and the username argument value if it contains any URI- or (X)HTML-special characters. For example:

// …
username = username.replace(/[\]\\^$*+?.(){}[]/g, "\\$&");
var rx = new RegExp("(^|\\s)(" + username + ")([\\s:;,]|$)", "gi");

var result = input.replace(rx, function (match, paren1, username, paren3) {
  return (paren1 + '<a href="…/' + encodeURIComponent(username) + '">'
    + username.replace(/&/g, "&amp;").replace(/</g, "&lt;")
    + '<\/a>' + paren3);
});

(See also jsx.regexp.escape in JSX:regexp.js.)

You may want to enhance this depending on what you consider to be a "url" etc. See RFC 3986, Appendix B, for a Regular Expression to match URIs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.