在点后添加空格,但不在 URL 中添加空格

Adding space after dot but not in URL

本文关键字:添加 空格 URL      更新时间:2023-09-26

我有一个文本,其中的句子在点后可能没有空格,例如:

另请参阅增值。关于这个术语的构造比比皆是。

如何在不在域名前面的点后添加空格?文本可能包含如下网址:

另请参阅增值。关于这个术语的构造比比皆是。http://example.com/foo/bar

匹配并捕获一个 URL,然后只匹配所有其他点以替换为点+空格:

var re = /((?:https?|ftps?):'/'/'S+)|'.(?!'s)/g; 
var str = 'See also vadding.Constructions on this term abound.'nSee also vadding.Constructions on this term abound. http://example.com/foo/bar';
var result = str.replace(re, function(m, g1) {
	return g1 ? g1 : ". ";
});
document.body.innerHTML = "<pre>" + result + "</pre>";

URL 正则表达式 - (?:https?|ftps?):'/'/'S+ - 匹配httphttpsftpftps,然后是://和1+非空格('S+)。它是基本的之一,您可以使用更复杂的方法,您可以在SO上轻松找到。例如,请参阅什么是匹配 URL 的良好正则表达式?

更详细的方法

((?:https?|ftps?):'/'/'S+)|'.(?!'s)正则表达式有 2 种选择:URL 匹配部分(如上所述)或 ( | ) 点匹配部分 ( '.(?!'s) )。

请注意,(?!'s)是一个负面的前瞻,允许匹配不跟空格的点。

当我们运行string.replace()时,我们可以指定一个匿名回调函数作为第二个参数,并将匹配和分组参数传递给它。因此,在这里,我们有 1 个匹配值 ( m ) 和 1 个捕获组值g1(URL)。如果 URL 匹配,则g1不为空。 return g1 ? g1 : ". ";意味着如果匹配了组 1,我们不会修改它,如果不匹配,我们匹配了一个独立的点,因此,我们替换为 . .

如果没有后跟两个或三个小写字母或空格字符,您可以尝试使用 RegExp /('.)(?!=[a-z]{2}'/|[a-z]{3}'/|'s+|$)/g 来匹配.字符

"See also vadding.Constructions on this term abound. http://example.com/foo/bar"
.replace(/('.)(?!=[a-z]{2}'/|[a-z]{3}'/|'s+|$)/g, "$1 ")

使用@MarcelKohls的想法

var text = "See also vadding.Constructions on this term abound. http://example.com/foo/bar";
var url_re = /('bhttps?:'/'/(?:(?:(?!&[^;]+;)|(?=&amp;))[^'s"'<>']'[)])+'b)/gi;
text = text.split(url_re).map(function(text) {
  if (text.match(url_re)) {
    return text;
  } else {
    return text.replace(/'.([^ ])/g, '. $1');
  }
}).join('');
document.body.innerHTML = '<pre>' + text + '</pre>';

使用此模式:

/'.(?! )((?:ftp|http)[^ ]+)?/g

在线演示