简体   繁体   中英

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.

You can use:

var repl = string.replace(/([^\s-])-\n/g, "$1");

RegEx Demo

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM