Search code examples
javascriptregexnegative-lookbehind

Negative Lookbehind: Match a substring that's not preceded one of a set of characters


Question

How do you define a regular expression that will match each substring that:

  • ends a line
  • is not preceded by one of a given set of characters

Case

I have a function that removes hardcoded newlines from strings of text, so they will reflow properly. The function works fine, apart from intelligently handling hyphenation.

This is a simplified version of what I have for hyphens.

function (string) { return string.replace(/-\n/g, "") }

It works on things it should work on, no problem. So this...

A hyphen-
ated line.

...becomes...

A hyphenated line.

But it goes too far, and doesn't handle dashes properly, so these examples get garbled:

"""
Mary Rose sat on a pin -
Mary rose.

Mary Rose sat on a pin --
Mary rose.
"""

The function should only consider the -\n pattern a match if it's not preceded by a hyphen or any kind of whitespace character.


Solution

  • You can change your pattern to this:

    function (string) { return string.replace(/\b-\n/g, "") }
    

    With a word boundary \b that is the limit between a word character and an other character.