簡體   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