需要做一些模式匹配与javascript

Needing to do some pattern matching with javascript

本文关键字:模式匹配 javascript      更新时间:2023-09-26

有一个用户输入的长字符串。使用javascript,我想得到第一句话的文本,如果它以问号结束。有什么简单的方法吗?

例如:

var myText1 = "What is your name? My name is Michelle."

我需要返回:"What is your name"

var myText2 = "this is a test. this is a test."

我需要返回:"n/a"

正则表达式:

var res = str.match(/^([^.]+)'?/);
var output = (res == null) ? 'n/a' : res[1];

我很困惑,这将是如何实际,但这应该工作。

var text = "this is a question? this is some text.";
var split1 = text.split(/[.?]+/); // splits the text at "." and "?"
var split2 = text.split(/[?]+/); // splits the text at "?"

// if the first element in both arrays is the same, the first sentence is a question.
var result = (split1[0] == split2[0]) ? split1[0] : "n/a";

根据美式英语语法规则,句子以., ?!结尾,但如果句子以引号结尾,则"将跟随(他对我说,"How are you doing?")。这算问题吗?这个句子本身是一个引问句的陈述句,所以我假设答案是否定的。这使它更容易,因为我们只需要考虑?后面没有"

考虑到以上,我的解决方案是:

function startIsQuestion( str ) {
  var m = str.match(/^[^.!]+[?][^"]/);
  if (!m || 
      m[0].indexOf('.') >= 0 ||
      m[0].indexOf('!') >= 0 ||
      m[0].indexOf('?"') >= 0) return "n/a";
  return m[0];
}

我不认为它完全健壮,但我不确定你的全部需求,它应该给你一个好的开始。

<<p> 看到演示/strong>