Javascript 捕获段落中的所有问题
我一直在尝试使用Javascript的正则表达式来解析给定段落中的每个问题。但是,我得到了不想要的结果: JavascriptJavascript 捕获段落中的所有问题,javascript,regex,parsing,Javascript,Regex,Parsing,我一直在尝试使用Javascript的正则表达式来解析给定段落中的每个问题。但是,我得到了不想要的结果: 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."
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."]
预期结果
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."]
实际结果
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."]
附言:如果有更好的方法,我洗耳恭听 试试这个:
var x = string.match(/\(?[A-Z][^\.!\?]+[!\.\?]\)?/g);
x.filter(function(sentence) {
return sentence.indexOf('?') >= 0;
})
试试这个:
var x = string.match(/\(?[A-Z][^\.!\?]+[!\.\?]\)?/g);
x.filter(function(sentence) {
return sentence.indexOf('?') >= 0;
})
JavaScript正则表达式选项的
.exec
方法仅返回与捕获的第一个匹配项。它还使用匹配字符串中的位置更新regex对象。这就是允许您使用.exec
方法循环遍历字符串的原因(也是您仅获得第一个匹配项的原因)
尝试改用字符串对象的.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?"
]
JavaScript正则表达式选项的
.exec
方法仅返回与捕获的第一个匹配项。它还使用匹配字符串中的位置更新regex对象。这就是允许您使用.exec
方法循环遍历字符串的原因(也是您仅获得第一个匹配项的原因)
尝试改用字符串对象的.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?"
]
输出:
[ 'Where are you?',
'How did you get there?' ]
输出:
[ 'Where are you?',
'How did you get there?' ]
不客气,你为什么要换答案?功能上是一样的afaik,虽然新的是一个稍微短一点的正则表达式。我发现你的过滤器和短一点的正则表达式相结合是最好的方法。我希望我能选择两者都是最好的:)不用担心,谢谢,只是确保我没有错过一些微妙的问题。不客气,你有什么理由交换答案吗?功能上是一样的afaik,虽然新的是一个稍微短一点的正则表达式。我发现你的过滤器和短一点的正则表达式相结合是最好的方法。我希望我能选择两者都是最好的:)不用担心,谢谢,只是确保我没有错过一些微妙的问题。