我希望使用JavaScript(也可以使用jQuery)来检查一个字符串是否匹配正则表达式^([a-z0-9]{5,})$
,并且得到true
或false
的结果。
match()
看起来是用来检查部分字符串是否匹配正则表达式,而不是整个字符串。它能解决这个问题吗?我能否通过修改适应它来解决这个问题?如何实现?
我希望使用JavaScript(也可以使用jQuery)来检查一个字符串是否匹配正则表达式^([a-z0-9]{5,})$
,并且得到true
或false
的结果。
match()
看起来是用来检查部分字符串是否匹配正则表达式,而不是整个字符串。它能解决这个问题吗?我能否通过修改适应它来解决这个问题?如何实现?
请尝试这朵花:
/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('abc@abc.abc');
真
let reg = /[a-zA-Z0-9]+/g
let txt = "hello"
let matches = reg.exec(txt)[0] == txt
console.log(`It ${matches ? "does" : "doesn't"} match`)
function updateUrlParameter(url, param, value) {
var regex = new RegExp("(?<=[?|&])(" + param + "=)[^&]+", "i");
if (regex.test(url)) {
return url.replace(regex, param + "=" + value);
} else {
if (window.location.search) {
return `${url}&${param}=${value}`;
}else{
return `${url}?${param}=${value}`;
}
}
}
match()
似乎检查字符串的一部分是否匹配正则表达式,而不是整个字符串。这样可以解决问题吗?我该如何改进它以解决问题?
是的,你可以。如果愿意,^
和 $
不是必需的。
思路很简单:.match()
返回一个“匹配”数组。如果第一个元素(即完整的匹配或 $0
)等于字符串,则表示完全匹配。
function fullMatch(string, regex) {
const match = string.match(regex);
return match?.[0] === string;
}
试一下:
console.config({ maximize: true });
function fullMatch(string, regex) {
const match = string.match(regex);
console.log(match);
return match?.[0] === string;
}
const string = 'f00bar';
const testcases = [
/\d+c?ba/, // false
/f\d+\w+/, // true
/[0a-z]+/g // false
];
testcases.forEach(
regex => console.log(fullMatch(string, regex))
);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
RegExp#exec()
来替代。function fullMatch(string, regex) {
const match = regex.exec(regex);
return match?.[0] === string;
}
试一下:
console.config({ maximize: true });
function fullMatch(string, regex) {
const match = regex.exec(string);
console.log(match);
return match?.[0] === string;
}
const string = 'f00bar';
const testcases = [
/\d+c?ba/, // false
/f\d+\w+/, // true
/[0a-z]+/g // true
];
testcases.forEach(
regex => console.log(fullMatch(string, regex))
);
<script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
一行代码:
const fullMatch = (string, array) => regex.exec(string)?.[0] === string;
调用RegExp.prototype.test()
可能是正确的,但有一些注意事项:
/g
,它实际上会存储状态,来自MDN:当设置了全局或粘性标志(例如 /foo/g 或 /foo/y)时,JavaScript RegExp 对象是有状态的。它们从先前的匹配中存储 lastIndex... https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
这意味着,对于第一个要点,您需要使用锚点,其中^
表示字符串的开头,$
表示字符串的结尾。因此,匹配完整字符串“Cat”且没有其他内容的正则表达式将是:/^Cat$/
regex.test(str)
来实现此目的,因为它的含义会随时间而变化。例如(请注意失败,尽管使用了不同的字符串实例)reg = /t/g;
console.log(reg.lastIndex); // 0 -- Never run
console.log(reg.test("Cat")); // true -- Matched "t"
console.log(reg.lastIndex); // 3 -- 3rd character was "t"
console.log(reg.test("Cat")); // false -- no more matches!
match
不需要整个字符串与正则表达式匹配。但是,^
和$
锚点确保此正则表达式只能可能与整个字符串匹配 - 这就是它们的目的。 - Karl Knechtel