从段落中捕获所有问题

时间:2013-01-08 20:58:58

标签: javascript regex parsing

我一直在尝试使用Javascript的RegEx来解析给定段落中的每个问题。但是,我得到了不必要的结果:

的Javascript

regex = /(\S.+?[.!?])(?=\s+|$)/g;
result = regex.exec("I can see you. Where are you? I am here! How did you get there?");

预期结果

["Where are you?", "How did you get there?"]

实际结果

["I can see you.", "I can see you."]

PS:如果有更好的方法,我会全力以赴!

3 个答案:

答案 0 :(得分:2)

试试这个:

var x = string.match(/\(?[A-Z][^\.!\?]+[!\.\?]\)?/g);
x.filter(function(sentence) {
  return sentence.indexOf('?') >= 0;
})

答案 1 :(得分:1)

JavaScript正则表达式选项的.exec方法仅返回与捕获的第一个匹配项。它还使用匹配字符串中的位置更新regex对象。这是允许您使用.exec方法循环字符串的原因(以及为什么您只获得第一个匹配)。

尝试使用String对象的.match方法:

regex = /(\S.+?[.!?])(?=\s+|$)/g;
result = ("I can see you. Where are you? I am here! How did you get there?").match(regex);

这给出了预期的结果:

[
    "I can see you.",
    "Where are you?",
    "I am here!",
    "How did you get there?"
]

答案 2 :(得分:1)

regex = / ?([^.!]*)\?/g;
text = "I can see you. Where are you? I am here! How did you get there?";
result = [];
while (m = regex.exec(text)) {
  result.push(m[1])
}

输出:

[ 'Where are you?',
  'How did you get there?' ]