所以我在多個專案中看到了這種情況,我不知道這里發生了什么。請幫我揭開這個神秘面紗。
假設您有一個正則運算式:
/^(hello|goodbye)?\s*world$/gi
并且您想針對以下字串對其進行測驗:
...
"hello world", // PASSES
"goodbye world", // PASSES
"hello goodbye", // FAILS
"world world" // FAILS
...
所以你使用 test 方法來評估字串以及它們是否通過:
...
/^(hello|goodbye)?\s*world$/gi.test(searchTexts[0])
你會得到你期望的結果。但是,現在您需要將正則運算式分配給一個變數(您知道,要重用它):
...
const helloWorldRegex = /^(hello|goodbye)?\s*world$/gi
突然之間,這不起作用:
...
new RegExp(helloWorldRegex).test(searchTexts[0]) // fails
helloWorldRegex.test(searchTexts[0]) // fails
是什么賦予了?我不知道
我所知道的是下面的 HACK 毫無意義,我想要一個解釋:
...
const hackedRegex = new RegExp(/^(hello|goodbye)?\s*world$/gi)
searchTexts[0].match(hackedRegex)
const hackedRegexPasses = hackedRegex.test(searchTexts[0])
下面的代碼是同構的,可以在瀏覽器或節點中作業,無論您喜歡還是在此處運行:https : //jsfiddle.net/qLm5679z/72/
const poutput = (text) => {
if (typeof window !== 'undefined') {
if (!document.getElementById("out")) document.body.innerHTML = "<div id='out'></div>"
const outputEl = document.getElementById("out")
outputEl.innerHTML = `<p>${(Array.isArray(text) ? text : [text]).join('<br>')}</p>`
}
console.log(text)
}
const searchTexts = [
// Using the regex = /^(hello|goodbye)?\s*world$/gi
"hello world", // PASSES
"goodbye world", // PASSES
"hello goodbye", // FAILS
"world world" // FAILS
]
const assignedRegex = /^(hello|goodbye)?\s*world$/gi
const constructedRegex = new RegExp(/^(hello|goodbye)?\s*world$/gi)
const nonLiteral = new RegExp("^(hello|goodbye)?\\s*world$", "gi")
const nonGlobal = new RegExp("^(hello|goodbye)?\\s*world$", "i")
for (const search of searchTexts) {
const inlineRegexPasses = /^(hello|goodbye)?\s*world$/gi.test(search)
const assignedRegexPasses = assignedRegex.test(search)
const constructedRegexPasses = constructedRegex.test(search)
const nonLiteralRegexPasses = nonLiteral.test(search)
const nonGlobalRegexPasses = nonGlobal.test(search)
const hackedRegex = new RegExp(/^(hello|goodbye)?\s*world$/gi)
search.match(hackedRegex)
const hackedRegexPasses = hackedRegex.test(search)
poutput([
`${search}::inlineRegexPasses::${inlineRegexPasses ? 'PASS' : 'FAIL'}`,
`${search}::nonGlobalRegexPasses::${nonGlobalRegexPasses ? 'PASS' : 'FAIL'}`,
`${search}::hackedRegexPasses::${hackedRegexPasses ? 'PASS' : 'FAIL'}`,
`${search}::assignedRegexPasses::${assignedRegexPasses ? 'PASS' : 'FAIL'}`,
`${search}::constructedRegexPasses::${constructedRegexPasses ? 'PASS' : 'FAIL'}`,
`${search}::nonLiteralRegexPasses::${nonLiteralRegexPasses ? 'PASS' : 'FAIL'}`
])
}
uj5u.com熱心網友回復:
在這里回答:為什么帶有全域標志的 RegExp 會給出錯誤的結果?
簡短說明:“g”標志使RegExp有狀態并保持最后一個索引來自最后一個match/ test。
此外,使用文字呼叫建構式使其共享文字的狀態。如果您希望建構式創建一個RegExp具有干凈狀態的新物件,則需要使用字串模式和標志引數呼叫它,如下所示:
new RegExp("^(hello|goodbye)?\\s*world$", "i")
uj5u.com熱心網友回復:
我使用https://regexr.com/來解決正則運算式的問題。我不保留這些資訊,當我需要它時,我會使用出現在本網站上的驗證器。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/356420.html
標籤:javascript 节点.js 正则表达式 浏览器
下一篇:如何在撇號內插入EJS標簽?
