简体   繁体   English

使用标签创建正则表达式?

[英]Create a regular expression with the tags?

There are three lines on the pages (000) 000-0-000 and +00 (000) 000-00-00 so I wrote a regular expression that searches for them /([\\+]?[0-9]+\\s)?[\\(][0-9]+[\\)]?[\\s][0-9-]+/ , but the third string is enclosed in tags <strong>(0000)</strong><span>00-00-00</span> how to modify the expression to come across and the third row? 页面上有三行(000)000-0-000和+00(000)000-00-00所以我写了一个正则表达式来搜索它们/([\\+]?[0-9]+\\s)?[\\(][0-9]+[\\)]?[\\s][0-9-]+/ ,但第三个字符串包含在标签<strong>(0000)</strong><span>00-00-00</span>如何修改表达式和第三行?

function PhoneReplace(){
            var src = $('body').html().replace(/([\+]?[0-9]+\s)?[\(][0-9]+[\)]?[\s][0-9-]+/g, '098 907 23 42');
            $('body').html(src);

        };

tags can not be deleted, I must be replaced 标签无法删除,我必须更换

Don't catch that case in your existing regular expression. 不要在现有的正则表达式中捕获该情况。 Instead, modify the string before you apply your phone number expression, ie remove the tags. 而是在应用电话号码表达式之前修改字符串,即删除标签。 There are many ways to do so, eg use a DOM parser, regexes might not be the best tool for that. 有很多方法可以做到这一点,例如使用DOM解析器,正则表达式可能不是最好的工具。 You could do 你可以做到

var results = input.replace(/<[^>]+>/g,"").match(myPhoneNumberExpression);

to remove all tag-like things. 删除所有标记之类的东西。

var s = '<strong>(0000)</strong><span>00-00-00</span>';
var n = '', result;
var regex = /(\+?\d+)/g;
while ((result = regex.exec(s))) { 
  n += result[1];
} 
document.writeln(n);

Check this code here . 在这里查看此代码。

You can use document.body.innerText or document.body.textContent to get at the textual content (without tags) of the HTML and you can then apply your phone# regular expression. 您可以使用document.body.innerTextdocument.body.textContent来获取HTML的文本内容(没有标记),然后您可以应用您的手机#正则表达式。

If the textual content doesn't help, then Strip HTML from Text JavaScript explains several (hacky) ways to remove tags from a string of HTML. 如果文本内容没有帮助,那么从Text JavaScript中删除HTML会解释几种(hacky)方法从HTML字符串中删除标记。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM