0

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.

4

2 回答 2

2

您可以将模式更改为:

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

单词边界\b是单词字符和其他字符之间的限制。

于 2014-11-08T17:03:07.187 回答
2

您可以使用:

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

正则表达式演示

于 2014-11-08T16:17:44.250 回答