简体   繁体   English

正则表达式匹配句子结尾标点而不删除分隔符并加入<p>标签</p>

[英]Regex to match sentence ending punctuation without removing delimiter and join <p> tag

I need to match all sentence ending punctuation in text file getting passed through to an html page by ajax in json format while keeping the delimiter and joining a <p> tag to each sentence.我需要匹配通过 ajax 以 json 格式传递到 html 页面的文本文件中的所有句子结尾标点符号,同时保持每个句子标记并加入<p>

Current code as follows:当前代码如下:

var xhr = new XMLHttpRequest();

xhr.onload = function() {
  if(xhr.status === 200) {
    responseObject = JSON.parse(xhr.responseText);

    var newContent = '';

    // text file html encasing
    newContent += '<p>' + responseObject.content + '</p>';

    // regex
    matchedPunctuation = newContent.match(/.*?[?!.]/g);

    // add element
    document.getElementById('myptag').innerHTML = matchedPunctuation.join('<p>');


  }
};

xhr.open('GET', 'http://127.0.0.1:5000/jsonstory', true);
xhr.send(null);

This fails me when I have a sentence as follows:当我有如下句子时,这让我失望:

Short text file EXAMPLE....... It is a nice day outsite.短文本文件示例.......这是一个美好的一天。 Dave said, "Yes it is."戴夫说:“是的。”

The code above would add <p> tags to the first sentence correctly, which would be directly after the period but before the start of the next sentence.上面的代码会正确地将<p>标记添加到第一句,这将直接在句点之后但在下一个句子的开头之前。

The second sentence adds them between the period and quotation .<p></p> "<p></p> which puts the quotation in a separate line from the sentence it should stay with on my html file. Any ideas or solutions would be appreciated.Thanks.第二句将它们添加在句点和引号之间.<p></p> "<p></p>将引号与我的 html 文件中应该保留的句子放在单独的行中。任何想法或解决方案将不胜感激。谢谢。

Try this regex .*?[?.?]"? The "?试试这个正则表达式.*?[?.?]"? "? makes it an optional requirement if the double quote is there or not.如果双引号存在或不存在,则使其成为可选要求。 If it is, it uses it first for the match, if not, it just carries on.如果是,则首先将其用于匹配,如果不是,则继续进行。

Hopefully, this helps.希望这会有所帮助。

var xhr = new XMLHttpRequest();

xhr.onload = function() {
  if(xhr.status === 200) {
    responseObject = JSON.parse(xhr.responseText);

    var newContent = '';

    // text file html encasing
    newContent += '<p>' + responseObject.content + '</p>';

    // regex
    matchedPunctuation = newContent.match(/.*?[?!.]"?/g);

    // add element
    document.getElementById('myptag').innerHTML = matchedPunctuation.join('<p>');


  }
};

xhr.open('GET', 'http://127.0.0.1:5000/jsonstory', true);
xhr.send(null);

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

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