1

我一直在尝试使用 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:如果有更好的方法可以做到这一点,我全神贯注!

4

3 回答 3

2

试试这个:

var x = string.match(/\(?[A-Z][^\.!\?]+[!\.\?]\)?/g);
x.filter(function(sentence) {
  return sentence.indexOf('?') >= 0;
})
于 2013-01-08T21:11:03.933 回答
1

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

尝试改用.matchString 对象的方法:

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?"
]
于 2013-01-08T21:18:24.677 回答
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?' ]
于 2013-01-08T21:25:50.423 回答