如何通过忽略数字句点的标点符号拆分字符串

时间:2021-03-01 11:59:07

标签: javascript regex

我在 javascript 中使用以下代码将字符串拆分为短语。

var result = str.match( /[^\n\.!\?\;:]+[\n\.!\?\;:]+/g );
let elements = result.map(element => element.trim());
elements = elements.filter(function (el) {return el != null && el != "";});

它工作正常。我的问题是当字符串中有数千个数字用点标记时,有些人使用像 1.500。如果标点符号后跟一个空格,如何改变它以便它只分隔短语。

1 个答案:

答案 0 :(得分:1)

你可以使用

/(?:[^\n.!?;:]|[\n.!?;:](?!\s))+[\n.!?;:]+/g

参见regex demo。关键是你要么匹配除所选标点符号以外的任何字符,要么匹配一个不跟空格的标点符号,一次或多次,然后匹配一个或多个你选择的标点符号。

详情

  • (?: - 非捕获组的开始:
    • [^\n.!?;:] - 除换行符以外的任何字符、.!?;:
  • | - 或
    • [\n.!?;:](?!\s) - 换行符、.!?;: 后不跟空格
  • )+ - 一次或多次
  • [\n.!?;:]+ - 一个或多个换行符、.!?;: 个字符。

查看 JavaScript 演示:

var s = 'It works ok. My problem is when the string has numbers in the thousands marked with a dot that some people use like 1.500. How can alter this so that it only separates the phrases if the punctuation is followed by a space.';
var rx = /(?:[^\n.!?;:]|[\n.!?;:](?!\s))+[\n.!?;:]+/g;
console.log( s.match(rx) );