简体   繁体   English

匹配开头和结尾的单词

[英]Match Word that Starts and Ends with

This must be somewhere... but after wasting quite a bit of time, I can't find it: I would like to test a string matching: "in"+ * +"ing" .这一定在某个地方......但是在浪费了相当多的时间之后,我找不到它:我想测试一个字符串匹配: "in"+ * +"ing"

In other words,换句话说,
" in terest ing " should result in true , whereas terest ING”应该产生true ,而
" in sist" and "str ing " should fail. SIST”和“海峡ING”应该失败。

I am only interested in testing a single word , with no spaces.我只对测试一个没有空格的单词感兴趣。

I know I could do this in two tests, but I really want to do it one.我知道我可以通过两次测试来做到这一点,但我真的很想做一次。 As always, thanks for any help.与往常一样,感谢您的帮助。

If you specifically want to match words then try something like this:如果您特别想匹配单词,请尝试以下操作:

/in[a-z]*ing/i

If you want "in" followed by any characters at all followed by "ing" then:如果你想要“in”后跟任何字符,然后是“ing”,那么:

/in.*ing/i

The i after the second / makes it case insensitive.第二个/之后的i使其不区分大小写。 Either way replace the * with + if you want to have at least one character in between "in" and "ing";无论哪种方式,如果您希望在“in”和“ing”之间至少有一个字符,请将*替换为+ * matches zero or more. *匹配零个或多个。

Given a variable in a string you could use the regex to test for a match like this:给定字符串中的变量,您可以使用正则表达式来测试这样的匹配:

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

UPDATE更新

"What if the prefix and suffix are stored in variables?" “如果前缀和后缀存储在变量中呢?”

Well then instead of using a regex literal as shown above you'd use new RegExp() and pass a string representing the pattern.那么,不是使用如上所示的正则表达式文字,而是使用new RegExp()并传递一个表示模式的字符串。

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

All of the regular expressions I've shown so far will match the "in" something "ing" pattern anywhere within a larger string.到目前为止,我展示的所有正则表达式都将匹配更大字符串中任何地方的“in” something“ing”模式。 If the idea is to test whether the entire string matches that mattern such that "interesting" would be a match but "noninterestingstuff" would not (as per stackunderflow's comment) then you need to match the start and end of the string with ^ and $ :如果想法是测试整个字符串是否与重要匹配,使得“有趣”将是匹配但“非有趣的东西”不会(根据 stackunderflow 的评论),那么您需要将字符串的开头和结尾与^$匹配:

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

Or from variables:或从变量:

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

Or if you're testing the whole string you don't necessarily need regex (although I find regex simpler):或者,如果您正在测试整个字符串,则不一定需要正则表达式(尽管我发现正则表达式更简单):

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
}

Or for browsers that don't support .endsWith() :或者对于不支持.endsWith() 的浏览器:

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

"What's the best I can read on the subject?" “关于这个主题,我能读到的最好的书是什么?”

MDN gives a rundown of regex for JavaScript. MDN提供了 JavaScript 正则表达式的纲要。 regular-expressions.info gives a more general set of tutorials.正则表达式.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.

If you wanted to constrain things to just one word, you could use the \\w word character shorthand.如果您想将事物限制在一个单词中,您可以使用\\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

The regex you're looking for is /in.*ing/ (this includes all characters).您正在寻找的正则表达式是/in.*ing/ (这包括所有字符)。

If you're more interested in single words, use a character class /in[az]*ing/如果您对单个单词更感兴趣,请使用字符类/in[az]*ing/

You can add the i flag if you're not interested in case.如果您对 case 不感兴趣,可以添加i标志。

I would recommend matching word boundary as well.我也建议匹配词边界。

Here's a fully parameterized version:这是一个完全参数化的版本:

Code代码

(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");

Output输出

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

Just expand the test string array and see what happens without the \\b .只需展开测试字符串数组,看看没有\\b会发生什么。

If in in the first rule can be part of ing (the second rule) use如果in在第一条规则中可以是ing (第二条规则)的一部分,则使用

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

See proof .证明

Explanation说明

--------------------------------------------------------------------------------
  \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))

If in can't be part of ing use如果in不能成为ing使用的一部分

/\bin\w*ing\b/g

See proof .证明

Explanation说明

--------------------------------------------------------------------------------
  \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 *: 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