这是一个非常简单的正则表达式问题,但是geez并不像所有其他答案所假设的那样直截了当。有几点:
正则表达式是正确的选择 - split
和substr
答案不会与领先的空间处理,并在一个句子的开头,一个破折号界线不能区分,并你的文字内容中间有一个破折号。您使用的任何选项都应该能够处理以下内容:"President Nicolas Sarkozy — running from behind for reelection — came to Paris today..."
以及您建议的选项。
自动识别我的测试句子没有日期线很困难。到目前为止,几乎所有的答案都使用单一描述:any number of arbitrary characters, followed by a dash
。这对于上面的测试句子来说是不够的。
通过添加更多规则,您将获得更好的结果,如fewer than X characters, located at the beginning of the string, followed by a dash, optionally followed by an arbitrary number of spaces, followed by a capital letter
。即使这不会与"President Sarkozy — Carla Bruni's husband..."
正常工作,但你将不得不假设这种边缘情况是足够罕见的忽视。所有这一切都
为您提供了这样的功能:
function removeDateline(str) {
return str.replace(/^[^—]{3,75}—\s*(?=[A-Z])/, "");
}
其分解:
^
- 必须出现在字符串的开头。
[^—]{3,75}
- 比破折号其他
\s*
3至75个字符 - 可选空格
- (= [A-Z]) - 超前 - 下一个字符必须是大写字母。
用法:
var s = "PARIS — President Nicolas Sarkozy, running from behind for reelection...";
removeDateline(s); // "President Nicolas Sarkozy — running from behind for reelection..."
s = "PARIS — President Nicolas Sarkozy — running from behind for reelection...";
removeDateline(s); // "President Nicolas Sarkozy — running from behind for reelection..."
s = "CARURU, Colombia — Quite suddenly, the endless green of Amazonian forest...";
removeDateline(s); // "Quite suddenly, the endless green of Amazonian forest..."
公平的警告 - 几乎所有的答案,下面将导致文本块问题了)没有界线,和b)在文中破折号别的地方。 – nrabinowitz 2012-03-12 18:23:12