繁体   English   中英

匹配开头和结尾的单词

[英]Match Word that Starts and Ends with

这一定在某个地方......但是在浪费了相当多的时间之后,我找不到它:我想测试一个字符串匹配: "in"+ * +"ing"

换句话说,
terest ING”应该产生true ,而
SIST”和“海峡ING”应该失败。

我只对测试一个没有空格的单词感兴趣。

我知道我可以通过两次测试来做到这一点,但我真的很想做一次。 与往常一样,感谢您的帮助。

如果您特别想匹配单词,请尝试以下操作:

/in[a-z]*ing/i

如果你想要“in”后跟任何字符,然后是“ing”,那么:

/in.*ing/i

第二个/之后的i使其不区分大小写。 无论哪种方式,如果您希望在“in”和“ing”之间至少有一个字符,请将*替换为+ *匹配零个或多个。

给定字符串中的变量,您可以使用正则表达式来测试这样的匹配:

var str = "Interesting";
if (/in[a-z]*ing/i.test(str)) {
    // we have a match
}

更新

“如果前缀和后缀存储在变量中呢?”

那么,不是使用如上所示的正则表达式文字,而是使用new RegExp()并传递一个表示模式的字符串。

var prefix = "in",
    suffix = "ing",
    re = new RegExp(prefix + "[a-z]*" + suffix, "i");
if (re.match("Interesting")) {
    // we have a match
}

到目前为止,我展示的所有正则表达式都将匹配更大字符串中任何地方的“in” something“ing”模式。 如果想法是测试整个字符串是否与重要匹配,使得“有趣”将是匹配但“非有趣的东西”不会(根据 stackunderflow 的评论),那么您需要将字符串的开头和结尾与^$匹配:

/^in[a-z]*ing$/i

或从变量:

new RegExp("^" + p + "[a-z]*" + s + "$", "i")

或者,如果您正在测试整个字符串,则不一定需要正则表达式(尽管我发现正则表达式更简单):

var str = "Interesting",
    prefix = "in",
    suffix = "ing";
str = str.toLowerCase(); // if case is not important

if (str.indexOf(prefix)===0 && str.endsWith(suffix)){
   // match do something
}

或者对于不支持.endsWith() 的浏览器:

if (str.slice(0,prefix.length)===prefix && str.slice(-suffix.length)===suffix)

“关于这个主题,我能读到的最好的书是什么?”

MDN提供了 JavaScript 正则表达式的纲要。 正则表达式.info提供了一组更通用的教程。

/in.+ing/ // a string that has `in` then at least one character, then `ing`


/in.+ing/.test('interesting'); // true
/in.+ing/.test('insist');      // false
/in.+ing/.test('string');      // false

/in.+ing/.test('ining'); // false, .+ means at least one character is required.
/in.*ing/.test('ining'); // true, .* means zero or more characters are allowed.

如果您想将事物限制在一个单词中,您可以使用\\w单词字符速记。

/in\w+ing/.test('invents tiring') // false, space is not a "word" character.
/in.+ing/.test('invents tiring') // true, dot matches any character, even space

您正在寻找的正则表达式是/in.*ing/ (这包括所有字符)。

如果您对单个单词更感兴趣,请使用字符类/in[az]*ing/

如果您对 case 不感兴趣,可以添加i标志。

我也建议匹配词边界。

这是一个完全参数化的版本:

代码

(function(prefix, suffix, anchored, flags) {
    var tests = [
        "noninterestingtypo",
        "mining",
        "in8ping",
        "interesting"];
    var re = new RegExp(
    (anchored ? '\\b' : '') + prefix + '[a-z]+' + suffix + (anchored ? '\\b' : ''), flags);
    var reportMatch = function(value) {
        console.log(value.match(re) ? value + " matches" : value + " does not match");
    };
    tests.forEach(reportMatch);
})( /* prefix, suffix, anchored, flags */
    "in", "ing", true, "i");

输出

noninterestingtypo does not match
mining does not match
in8ping does not match
interesting matches

只需展开测试字符串数组,看看没有\\b会发生什么。

如果in在第一条规则中可以是ing (第二条规则)的一部分,则使用

/\b(?=in)(?=\w*ing\b)\w+/g

证明

说明

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    in                       'in'
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    \w*                      word characters (a-z, A-Z, 0-9, _) (0 or
                             more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    ing                      'ing'
--------------------------------------------------------------------------------
    \b                       the boundary between a word char (\w)
                             and something that is not a word char
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                           more times (matching the most amount
                           possible))

如果in不能成为ing使用的一部分

/\bin\w*ing\b/g

证明

说明

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  in                       'in'
--------------------------------------------------------------------------------
  \w*                      word characters (a-z, A-Z, 0-9, _) (0 or
                           more times (matching the most amount
                           possible))
--------------------------------------------------------------------------------
  ing                      'ing'
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

JavaScript *:

 const string = 'interesting,ing and bing.'; const rx_1 = /\\b(?=in)(?=\\w*ing\\b)\\w+/g; const rx_2 = /\\bin\\w*ing\\b/g; console.log(string.match(rx_1)); console.log(string.match(rx_2));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM