匹配单个单词,结尾可能是标点符号或复数(正则表达式)

时间:2013-02-13 16:59:23

标签: javascript regex

我在Regex上的表现越来越好,但我想出的东西超出了我目前的能力范围。

我想构建一个函数来测试(返回true或false)来测试是否在字符串中找到一个单词。但如果在另一个单词中找到这个单词,我不希望得到一个肯定的匹配。我还想建立检查复数的可能性。

以下是我希望得到的结果的一些例子:

要查找的字词:“bar”

“要搜索的字符串”//应该返回

“foo bar”// true

“foo bar。” //真

“foo bar!” // true(对于'bar'之前或之后的任何其他标点符号也是如此)

“foo bars。” //真

“foo bares。” // true(即使bares有不同的含义然后吧,我会好的,因为我需要检查带有“es”复数的单词,因为我需要检查带有“es”复数的单词,并且我不希望构建一个正则表达式来知道哪些单词用“s”复数,用“es”复数)

“我的名字是bart simpson”// false(酒吧实际上是“bart”的一部分)

“巴特辛普森去了酒吧。” //真

我将使用javascript / jquery来检查匹配

非常感谢你的帮助!

3 个答案:

答案 0 :(得分:4)

var rgx = new RegExp('\\b' + word + '(?:es|s)?\\b');
rgx.test(string);

这将为您在请求中指定的所有字符串返回true\b表示“单词边界”,我认为\W中的任何字符(包括句点和感叹号)以及字符串的开头或结尾。

答案 1 :(得分:2)

这已经得到了回答和接受,但我认为我会提供一种略微过度设计的方法,可以更好地匹配复数形式。除此之外,它使用与@ExplosionPills解决方案完全相同的逻辑:

(function() {
  var isWord = function(word) { return /^[a-z]+$/i.test(word); },

      exceptions = {
        man:   'men',
        woman: 'women',
        child: 'children',
        mouse: 'mice',
        tooth: 'teeth',
        goose: 'geese',
        foot:  'feet',
        ox:    'oxen'
      },

      pluralise = function(word) {
        word = word.toLowerCase();

        if (word in exceptions) {
          // Exceptions
          return '(?:' + word + '|' + exceptions[word] + ')';

        } else if (word.match(/(?:x|s|[cs]h)$/)) {
          // Sibilants
          return word + '(?:es)?';

        } else if (word.match(/[^f]f$/)) {
          // Non-Geminate Labio-Dental Fricative (-f > -ves / -fs)
          return '(?:' + word + 's?|' + word.replace(/f$/, 'ves') + ')';

        } else if (word.match(/[^aeiou]y$/)) {
          // Close-Front Unround Pure Vowel (-Cy > -Cies)
          return '(?:' + word + '|' + word.replace(/y$/, 'ies') + ')';

        } else if (word.substr(-1) == 'o') {
          // Mid-Back Round Vowel (-o > -oes / -os)
          return word + '(?:e?s)?';

        } else {
          // Otherwise
          return word + 's?';
        }
      };

  String.prototype.containsNoun = function(singularNoun) {
    if (!isWord(singularNoun)) throw new TypeError('Invalid word');
    var check = new RegExp('\\b' + pluralise(singularNoun) + '\\b', 'gi');
    return check.test(this);
  };

  String.prototype.pluralException = function(plural) {
    if (!isWord(this) || !isWord(plural)) throw new TypeError('Invalid exception');

    var singular = this.toLowerCase();
    plural = plural.toLowerCase();

    if (!(singular in exceptions)) {
      exceptions[singular] = plural;
    }
  };
})();

它扩展了原生String对象,因此您可以这样使用它:

'Are there some foos in here?'.containsNoun('foo'); // True

请参阅the gist,了解在Node.js中进行的一些快速和脏的单元测试。

答案 2 :(得分:0)

/ (bar((e)?s)?)[ !?.]/

取决于您的需求,这可能会起作用。 由于重叠的空格,它不会在字符串“bars bars”中找到两个小节。

/ (bar((e)?s)?)(?=[ !?.])/

应该可以使用js1.5以来的“吧栏”(两个匹配),现在所有浏览器都支持它。