JavaScript Split Regular Expression keep the delimiter

前端 未结 3 1945
没有蜡笔的小新
没有蜡笔的小新 2020-12-11 11:31

Using JavaScript I\'m trying to split a paragraph into it\'s sentences using regular expressions. My regular expression doesn\'t account for a sentence being inside bracket

相关标签:
3条回答
  • 2020-12-11 11:57

    @Utkanos You idea is good, but I think replace may better:

    text.replace(/\(?[A-Z][^\.]+[\.!\?]\)?/g, function (sentence) {
        output += '<p>'+ sentence + '</p>';
    });
    

    http://jsfiddle.net/juGT7/1/

    You no need to loop again.

    0 讨论(0)
  • 2020-12-11 11:59

    use the (?=pattern) lookahead pattern in the regex example

    var string = '500x500-11*90~1+1';
    string = string.replace(/(?=[$-/:-?{-~!"^_`\[\]])/gi, ",");
    string = string.split(",");
    

    this will give you the following result.

    [ '500x500', '-11', '*90', '~1', '+1' ]
    

    Can also be directly split

    string = string.split(/(?=[$-/:-?{-~!"^_`\[\]])/gi);
    

    giving the same result

    [ '500x500', '-11', '*90', '~1', '+1' ]
    
    0 讨论(0)
  • 2020-12-11 12:04

    I took the match approach rather than split. It could be tighter (e.g. what if a sentence ends with ..., etc).

    text.match(/\(?[A-Z][^\.]+[\.!\?]\)?(\s+|$)/g);
    

    http://jsfiddle.net/DepKF/1/

    0 讨论(0)
提交回复
热议问题