首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >与句子匹配而忽略标记内容的正则表达式会是什么样的呢?

与句子匹配而忽略标记内容的正则表达式会是什么样的呢?
EN

Stack Overflow用户
提问于 2013-01-02 17:47:47
回答 2查看 114关注 0票数 0

我试图用跨度标记来包装给定文本的单个句子,到目前为止,这是相当不错的。

$this.html().replace(/\b.*?[\.\?\!]/gi, "<span>$&<\/span>");

现在,在内容中已经出现了一些其他的span和b标记,如下所示:

Gumbo groundnut daikon radicchio scallion lettuce rock melon peanut. <span class="yellow">Catsear swiss chard epazote bush tomato peanut chicory amaranth tomato gourd.</span> Earthnut pea brussels sprout gumbo celery tomato salad kale. Spinach scallion tomatillo bitterleaf lentil <b>green</b> bean celery amaranth onion catsear sweet pepper fava bean silver beet spinach.

由于我不想去掉这些标记,也不想封装它们,所以解决方案可以是:

  1. 只需忽略标签和里面的内容
  2. 把标签当作句子的结尾和开头

最后它看起来会是这样的:

<span>Gumbo groundnut daikon radicchio scallion lettuce rock melon peanut. <span class="yellow">Catsear swiss chard epazote bush tomato peanut chicory amaranth tomato gourd.</span> <span>Earthnut pea brussels sprout gumbo celery tomato salad kale.</span> <span>Spinach scallion tomatillo bitterleaf lentil </span><b>green</b><span> bean celery amaranth onion catsear sweet pepper fava bean silver beet spinach.</span>

这样的正则表达式会是什么样子?我对此感到非常头痛,因为我的判断力还很有限。

EN

回答 2

Stack Overflow用户

发布于 2013-01-02 17:53:24

编写解析器,而不是正则表达式。要处理嵌套的HTML标记将非常困难,例如,只使用正则表达式。

票数 1
EN

Stack Overflow用户

发布于 2013-01-04 09:40:32

我现在已经实现了一个小功能,它或多或少地实现了我想要的功能。它基本上取代了所有的孩子(跨度,b,等等)使用占位符-元素,这样它们就不会弄乱正则表达式。稍后,我只需将占位符替换为原始子元素。这是一种快速而肮脏的解决方案,但就目前而言,它已经足够有效了。

代码语言:javascript
复制
function wrapSentences($element){
var j = 0, i = 0, placeholders = [];

 $.each($element.children(),function(){
     var p = $("<b id='p"+j+"'></b>");
     $(this).after(p).remove();
       placeholders.push($(this));
    j++;                              
 });

 $element.html($element.html().replace(/\(?[A-Z][^\.]+[\.!\?]\)?/g, "<span class='s'>$&<\/span>"));


 $.each(placeholders,function(){
       $element.find("#p"+i).replaceWith(this);
      i++;
 });
}

jsFiddle

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14126673

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档