检查字符串是否与 JS 中的正则表达式匹配

发布于 2024-11-18 13:51:52 字数 217 浏览 4 评论 0原文

我想使用 JavaScript(我也可以使用 jQuery)来检查字符串是否与正则表达式 ^([a-z0-9]{5,})$ 匹配,并获取 truefalse 结果。

match() 似乎检查字符串的一部分是否与正则表达式匹配,而不是整个字符串。它能解决问题吗?我可以调整它来解决问题吗?如何?

I want to use JavaScript (I can also use jQuery) to do check whether a string matches the regex ^([a-z0-9]{5,})$, and get a true or false result.

match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(15

池予 2024-11-25 13:51:52

使用 regex.test()如果您想要的只是布尔结果:

console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false

console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true

console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true

...并且您可以从正则表达式中删除 () 因为您不需要捕获。

Use regex.test() if all you want is a boolean result:

console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false

console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true

console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true

...and you could remove the () from your regexp since you've no need for a capture.

<逆流佳人身旁 2024-11-25 13:51:52

使用 test() 方法:

var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
    console.log("Valid");
} else {
    console.log("Invalid");
}

Use test() method :

var term = "sample1";
var re = new RegExp("^([a-z0-9]{5,})$");
if (re.test(term)) {
    console.log("Valid");
} else {
    console.log("Invalid");
}
泪痕残 2024-11-25 13:51:52

您也可以使用 match()

if (str.match(/^([a-z0-9]{5,})$/)) {
    alert("match!");
}

但是 test() 似乎更快,因为您可以阅读 这里

match()test() 之间的重要区别:

match() 仅适用于字符串,但 test() 也适用于整数。

12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345);  // true
/^([a-z0-9]{5,})$/.test(null);   // false

// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true

You can use match() as well:

if (str.match(/^([a-z0-9]{5,})$/)) {
    alert("match!");
}

But test() seems to be faster as you can read here.

Important difference between match() and test():

match() works only with strings, but test() works also with integers.

12345.match(/^([a-z0-9]{5,})$/); // ERROR
/^([a-z0-9]{5,})$/.test(12345);  // true
/^([a-z0-9]{5,})$/.test(null);   // false

// Better watch out for undefined values
/^([a-z0-9]{5,})$/.test(undefined); // true
风筝有风,海豚有海 2024-11-25 13:51:52

如果您只想知道字符串是否与正则表达式匹配,请使用 /youregexp/.test(yourString)

Use /youregexp/.test(yourString) if you only want to know whether your string matches the regexp.

深居我梦 2024-11-25 13:51:52

下面是一个查找某些 HTML 标签的示例,因此很明显 /someregex/.test() 返回一个布尔值:

if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');

如果您想测试整个字符串的精确匹配,请记住^ 表示字符串的开头,以 $ 表示结尾。

例子:

/[a-z]+/.test('aaa111'); // true
/^[a-z]+$/.test('aaa111'); // false

Here's an example that looks for certain HTML tags so it's clear that /someregex/.test() returns a boolean:

if(/(span|h[0-6]|li|a)/i.test("h3")) alert('true');

Remember to indicate ^ for beginning of the string and $ for the end, if you want to test the exact match of entire string.

Example:

/[a-z]+/.test('aaa111'); // true
/^[a-z]+$/.test('aaa111'); // false
云雾 2024-11-25 13:51:52
let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));

let str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
let regexp = /[a-d]/gi;
console.log(str.match(regexp));

半世蒼涼 2024-11-25 13:51:52
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't

const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't

谷夏 2024-11-25 13:51:52

尝试

 /^[a-z\d]{5,}$/.test(str)

console.log( /^[a-z\d]{5,}$/.test("abc123") );

console.log( /^[a-z\d]{5,}$/.test("ab12") );

try

 /^[a-z\d]{5,}$/.test(str)

console.log( /^[a-z\d]{5,}$/.test("abc123") );

console.log( /^[a-z\d]{5,}$/.test("ab12") );

琉璃梦幻 2024-11-25 13:51:52

我建议使用execute方法,如果不存在匹配则返回null,否则它返回一个有用的对象。

let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null

let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]

I would recommend using the execute method which returns null if no match exists otherwise it returns a helpful object.

let case1 = /^([a-z0-9]{5,})$/.exec("abc1");
console.log(case1); //null

let case2 = /^([a-z0-9]{5,})$/.exec("pass3434");
console.log(case2); // ['pass3434', 'pass3434', index:0, input:'pass3434', groups: undefined]
守护在此方 2024-11-25 13:51:52

你可以试试这个,它对我有用。

 <input type="text"  onchange="CheckValidAmount(this.value)" name="amount" required>

 <script type="text/javascript">
    function CheckValidAmount(amount) {          
       var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
       if(amount.match(a)){
           alert("matches");
       }else{
        alert("does not match"); 
       }
    }
</script>

You can try this, it works for me.

 <input type="text"  onchange="CheckValidAmount(this.value)" name="amount" required>

 <script type="text/javascript">
    function CheckValidAmount(amount) {          
       var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
       if(amount.match(a)){
           alert("matches");
       }else{
        alert("does not match"); 
       }
    }
</script>
逆光飞翔i 2024-11-25 13:51:52

请尝试一下这朵花:

/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('[email protected]');

正确

please try this flower:

/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('[email protected]');

true

岁月静好 2024-11-25 13:51:52

如果您不想在正则表达式周围使用 ^ 和 $ (我有这样的用例),您可以执行类似的操作

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

If you don't want ^ and $ around the regex (I had such a usecase) you can do something like

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`)
薄荷梦 2024-11-25 13:51:52

更新/添加

如果查询字符串不存在于 URL 中,则以下解决方案将在 URL 中添加参数,如果该参数已存在,则它将更新。

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}`;
    }
  }
}

Update/Add

If the query string does not present in the URL then the below solution will work to add the param in the URL, if it already exists then it will update.

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}`;
    }
  }
}

空气里的味道 2024-11-25 13:51:52

调用 RegExp.prototype.test() 可能是正确的,但有一些注意事项:

  • 它会告诉您字符串是否“匹配”正则表达式——即它是否“包含匹配序列”——不是字符串是否“完全匹配”。
  • 如果正则表达式是全局的 /g 它实际上存储来自 MDN 的状态:

JavaScript RegExp 对象在设置了全局或粘性标志(例如 /foo/g 或 /foo/y)时是有状态的。他们存储上一场比赛的lastIndex......
https://developer.mozilla.org/ en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

这意味着,对于第一点,您需要使用锚点,其中 ^ 表示 a 的开始字符串,$表示结束。因此,正则表达式匹配完整的字符串“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!

Calling RegExp.prototype.test() is probably correct, but has a couple caveats:

  • It will tell you whether a string "matches" a regex -- i.e. if it "contains a matching sequence" -- not whether the string is an "exact match".
  • If a regex is global /g it actually stores state, from the MDN:

JavaScript RegExp objects are stateful when they have the global or sticky flags set (e.g., /foo/g or /foo/y). They store a lastIndex from the previous match...
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test

This means, for the first point, you need to use anchors, where ^ indicates the start of a string, and $ indicates it's end. So a regex matching the full string "Cat" & nothing else would be: /^Cat$/

And secondly, you cannot reuse regex.test(str) with a global regex on the same string for this purpose, as it's meaning changes over time. E.g. (and note the failure, despite using different instances of string)

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!
静待花开 2024-11-25 13:51:52

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>

请注意,这不适用于 g 正则表达式,因为此标志会导致 .match() 在至少有一个匹配项的情况下始终返回普通数组。

但是,您可以使用 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;

match() seems to check whether part of a string matches a regex, not the whole thing. Does it solve the problem? Can I adapt it to solve the problem? How?

Yes, you can. ^ and $ are not needed if you so choose.

The idea is simple: .match() returns a "match" array. If the first element (i.e. the whole match, or $0) equals to the string, then we have a full match.

function fullMatch(string, regex) {
  const match = string.match(regex);
  return match?.[0] === string;
}

Try it:

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>

Note that this does not work with g regexes, as this flag causes .match() to always return a normal array if there is at least one match.

You can, however, use RegExp#exec() instead:

function fullMatch(string, regex) {
  const match = regex.exec(regex);
  return match?.[0] === string;
}

Try it:

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>

One-liner:

const fullMatch = (string, array) => regex.exec(string)?.[0] === string;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文