匹配开头和结尾的字词

Match Word that Starts and Ends with

本文关键字:字词 结尾 开头      更新时间:2023-10-02

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

换句话说,
">特雷斯特">应该导致true,而
">sist"和"string"应该失败。

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

我知道我可以在两个测试中做到这一点,但我真的很想做一个。与往常一样,感谢您的任何帮助。

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

/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"某物"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正则表达式的概要。 regular-expressions.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[a-z]*ing/

如果您对案例不感兴趣,可以添加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));