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 正規表現オプションの.execメソッドは、キャプチャとの最初の一致のみを返します。また、一致した文字列内の位置で正規表現オブジェクトを更新します。これが、メソッドを使用して文字列をループできるようにするものです.exec(そして、最初の一致のみを取得する理由)。

.match代わりに String オブジェクトのメソッドを使用してみてください。

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 に答える