【问题标题】:Capture all questions from a paragraph捕获段落中的所有问题
【发布时间】:2013-01-08 20:58:57
【问题描述】:

我一直在尝试使用 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:如果有更好的方法,我会全力以赴!

【问题讨论】:

    标签: javascript regex parsing


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • 不客气,你换答案的理由是什么?功能上相同的 afaik,虽然较新的是一个更短的正则表达式。
    • 您的过滤器与较短的正则表达式相结合是我发现的最佳方法。我希望我能将两者都选为最好的:)
    • 不用担心,谢谢,只是确保我没有错过一些微妙的问题。
    【解决方案2】:

    JavaScript regex 选项的.exec 方法只返回第一个匹配项。它还使用匹配字符串中的位置更新正则表达式对象。这就是允许您使用 .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?"
    ]
    

    【讨论】:

      【解决方案3】:
      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?' ]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-08
        • 1970-01-01
        • 1970-01-01
        • 2015-08-03
        相关资源
        最近更新 更多