user1745558 user1745558 - 1 month ago 4
Javascript Question

find all ":)" that are not surrounded by any character

I'm trying to change all ":)" (without quotes) to pictures. To make a match, a smiley must be surrounded by spaces (or be at the beginning or the end of a string).

My attempt:

/(?:^|\s)\:\)(?:$|\s)/g



if a smiley is (at the beginning of a string or has a white-space before it) and (is at the end of a string or has a white-space after it);


A string like that works fine: ":) x :) x :)"
but such string does not: ":) :) :) :)" (every second smiley is changed).

As I understand, the first smiley is matched with the space after it and the next smiley is neither at the beginning of a string or has a white-space anymore. I'm new to regular expressions and can't figure out how to fix my logic :)

P.S. maybe there is a shortcut to find a pattern that is not surrounded by any character? (
\b
and
\B
would not work for that)

Answer

How about the regex

(?:\s|^):\)(?=\s|$)

Example : http://regex101.com/r/zY9xA3/2

Problem with /(?:^|\s)\:\)(?:$|\s)/g

  • The \s after :) is consumed by the regex engine that for the second :) we cannot have a presceding \s

Solution

Use a positive look ahead so that the the space after is not consumed by the regex.

  • (?=\s|$) look ahead asserts that :) is followed by space or end of string. But wont consume the character.

Changes made

  • \: to : you need not escape the the :

  • (?:$|\s) non capturing group to positive look ahead (?=\s|$)