Tom*_*eus 0 javascript php regex
我需要在每个句子开头的短划线之前删除所有单词.有些句子在破折号之前没有单词,而长句子中的破折号需要保留.这是一个例子:
如何更改这些字符串:
巴黎 - 总统尼古拉·萨科齐(Nicolas Sarkozy)从后面跑来重新选举......
加沙城 - 加沙和以色列之间的跨境战斗......
哥伦比亚卡鲁鲁 - 突然之间,亚马逊森林的无尽绿色......
地震和海啸袭击日本东北沿海一年后......
进入这些字符串:
总统尼古拉·萨科齐(Nicolas Sarkozy)从后面跑来重新选举......
加沙和以色列之间的跨界战斗......
突如其来,亚马逊森林的无尽绿色......
地震和海啸袭击日本东北沿海一年后......
如何使用javascript(或php,如果javascript不允许)完成此操作?
这是一个相当简单的正则表达式问题,但是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])/, "");
}
Run Code Online (Sandbox Code Playgroud)
打破它:
^ - 必须出现在字符串的开头.[^—]{3,75} - 短划线以外的3到75个字符\s* - 可选空间用法:
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..."
Run Code Online (Sandbox Code Playgroud)