首页 > 解决方案 > 正则表达式搜索 Telefon 但跳过网址

问题描述

我有一个正则表达式,可以完美地处理我想要获取的数字,但问题在于也获取它们的 URL,我该如何删除它们?

如果没有空格、换行之类的就跳过?

谢谢 !!

我目前的正则表达式是:

/((?(0{1,2}|+)\d{1,2})?)?(([ -]*\d+){8,20})+/gm

https://regex101.com/r/yzAScj/1

我所做的修改不起作用:

/\s{1}((?(0{1,2}|+)\d{1,2})?)?(([ -]*\d+){8,20})+\s{0 ,1}/克

https://regex101.com/r/yzAScj/2

测试文本:

https://asd.com/20441235534-aaaaaaaaaaa-

202460676

aasdasd 202460676

https://asd.com/20441235534


202460676-



10 text
1234 text
text 123

00491234567890
+491234567890

0123-4567890

0123 4567 789
0123 456 7890
0123 45 67 789

+490123 4567 789
+490123 456 7890
+49 123 45 67 789

123 4567 789
123 456 7890
123 45 67 789


+49 1234567890
+491234567890

0049 1234567890
0049 1234 567 890

(0049)1234567890
(+49)1234567890

(0049) 1234567890
(+49) 1234567890



text text (0049) 1234567890 text text
text text (+49) 1234567890 text text

使电话号码具有链接“电话:”以便能够点击它们。

您不应该选择 URL 作为电话。

JS代码(带jquery):

函数 searchAndReplacePhones(){

    var regex =  /(\(?(0{1,2}|\+)\d{1,2}\)?)?(([ -]*\d+){8,20})+/gm;

    //Beschreibung
    $(".my_text").html($(".my_text").html().replace(regex, " <a href=\"tel:$&\">$&</a> "));

}

标签: regexregexp-replace

解决方案


您可以使用匹配 URL(例如 with https?://\S*)或匹配并捕获电话号码的正则表达式:

var regex = /https?:\/\/\S*|((?:\(?(?:0{1,2}|\+)\d{1,2}\)?[ -]*)?\d(?:[ -]*\d){7,19})/gi;

然后,在.replace方法中使用时,需要使用回调方法,在此传递正则匹配并分析匹配的结构:如果Group 1匹配,则替换它,否则,放回匹配值。

请参阅下面的正则表达式演示和 JS 演示:

var text = "\n\nhttps://asd.com/20441235534-aaaaaaaaaaa-\n\n202460676\n\naasdasd 202460676\n\nhttps://asd.com/20441235534\n\n\n202460676-\n\n\n\n10 text\n1234 text\ntext 123\n\n00491234567890\n+491234567890\n\n0123-4567890\n\n0123 4567 789\n0123 456 7890\n0123 45 67 789\n\n+490123 4567 789\n+490123 456 7890\n+49 123 45 67 789\n\n123 4567 789\n123 456 7890\n123 45 67 789\n\n\n+49 1234567890\n+491234567890\n\n0049 1234567890\n0049 1234 567 890\n\n(0049)1234567890\n(+49)1234567890\n\n(0049) 1234567890\n(+49) 1234567890\n\n\n\ntext text (0049) 1234567890 text text\ntext text (+49) 1234567890 text text";
var regex = /https?:\/\/\S*|((?:\(?(?:0{1,2}|\+)\d{1,2}\)?[ -]*)?\d(?:[ -]*\d){7,19})/gi;
//https://regex101.com/r/0LxWTv/5
document.body.innerHTML = "<pre>" + text.replace(regex, function($0,$1) {
  return $1 ? '<a href="tel:' + $1 + '">' + $1 + '</a>' : $0;
} ) + "</pre>";

注意我稍微修改了模式:

  • (?:\(?(?:0{1,2}|\+)\d{1,2}\)?[ -]*)?- 一个可选的非捕获组,匹配 1 次或 0 次出现
    • \(?
    • (?:0{1,2}|\+)- 一个或两个零或+
    • \d{1,2}- 一位或两位数
    • \)?- 一个可选的)
    • [ -]*- 0 个或多个空格或连字符
  • \d - 一个数字
  • (?:[ -]*\d){7,19}- 七到十九位数字,以 0 或多个空格或连字符分隔。

推荐阅读