Regular punctuation match punctuation option, but keep punctuation

I have a line of a large paragraph that I am trying to split into sentences using the JavaScript method .split(). I need a regular expression that matches a period or question mark [?.]followed by a space. However, I need to save the period / question mark in the resulting array. How can I do this without positive searches in JS?

Edit: Input "This is sentence 1. This is sentence 2? This is sentence 3." Example: Output Example: ["This is sentence 1.", "This is sentence 2?", "This is sentence 3."]

+4
source share
5 answers

This regex will work

([^?.]+[?.])(?:\s|$)

Regex Demo

Js demo

Perfect demonstration

var str = 'This is sentence 1. This is sentence 2? This is sentence 3.';
var regex = /([^?.]+[?.])(?:\s|$)/gm;
var m;

while ((m = regex.exec(str)) !== null) {
    document.writeln(m[1] + '<br>');
}
Run codeHide result
+1

split(). match()

var text = "This is an example paragragh. Oh and it has a question? Ok it followed by some other random stuff. Bye.";

var matches = text.match(/[\w\s'\";\(\)\,]+(\.|\?)(\s|$)/g);


alert(matches);

:

    Array[4]
        0:"This is an example paragragh. "
        1:"Oh and it has a question? "
        2:"Ok it followed by some other random stuff. "
        4:"Bye. "

: https://jsfiddle.net/uds4cww3/

, .

+1

,

\b.*?[?\.](?=\s|$)

Regular expression visualization

Debuggex

0

, :

var breakIntoSentences = function(s) {
  var l = [];
  s.replace(/[^.?]+.?/g, a => l.push(a));
  return l;
}

breakIntoSentences("how? who cares.")
["how?", " who cares."]

(, : RE -, -. , - , .)

, breakIntoSentences("how???? who cares...") ["how?", " who cares."]. , /[^.?]+[.?]*/g RE .

: : Wavvves match(), /push. , - .

, ES6, :

const breakIntoSentences = s => s.match(/[^.?,]+[.?,]*/g)
0

, .match :

(?:\s?)(.*?[.?])

..:

sentence = "This is sentence 1. This is sentence 2? This is sentence 3.";
result = sentence.match(/(?:\s?)(.*?[.?])/ig);
for (var i = 0; i < result.length; i++) {
   document.write(result[i]+"<br>");
}
Hide result
0

All Articles