×

快速提示:测试字符串是否与 JavaScript 中的正则表达式匹配

作者:Terry2022.12.14来源:Web前端之家浏览:2084评论:0
关键词:js

在这个关于 JavaScript 正则表达式匹配的简短教程中,您将学习如何使用 方法测试字符串是否与正则表达式匹配test()

字符串是可以包含各种数据的文本

当您测试字符串是否包含特定子字符串时,您可能倾向于使用类似indexOf(). 但是,对于更灵活的测试和条件,使用正则表达式是更好的选择。

JavaScript 正则表达式匹配允许您检查字符串是否包含特定模式、子字符串或字符类型。正则表达式对于检测可以以不同格式编写的字符串中的信息很有用,例如日期。

针对正则表达式测试字符串

要测试字符串是否与正则表达式匹配,您必须首先创建一个正则表达式实例。然后,您可以使用test()正则表达式上可用的方法来检查字符串是否与正则表达式匹配。

test()方法接受一个参数:要针对模式进行测试的字符串。它返回一个布尔值,指示字符串是否与正则表达式匹配。

例如:

片段,例如 URL、电话号码、姓名、号码等。在很多情况下,您需要检查字符串是否包含一段文本或某些类型的字符。

const pattern = /test.*regular/;
const str = 'I want to test this string against a regular expression';
if (pattern.test(str)) {
  console.log('Matched');
} else {
  console.log('Not Matched');
}

在此示例中,您创建模式test.*regular。此模式意味着字符串必须按顺序包含单词test和,并且这些单词可以由零次或多次出现的任何字符分隔。regular

如果test()返回 true,Matched则记录在控制台中。否则,Not Matched将记录在控制台中。

由于str包含单词testand regular,并且在字符串test之前,它将与模式匹配并返回 true。regulartest()

您还可以使用RegExp构造函数来声明模式:

const pattern = new RegExp('test.*regular');
const str = 'I want to test this string against a regular expression';
if (pattern.test(str)) {
  console.log('Matched');
} else {
  console.log('Not Matched');
}

您可以在以下 CodePen 演示中对此进行测试。

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
<meta charset="utf-8">
<style>
  .users {
    padding: 15px;
  }

  ul {
    margin-top: 15px;
  }
</style>
</head>
<body>
  <div>
    <label for="str">Enter string</label>
    <input type="text" name="str" id="str" />
  </div>
  <button id="check">Does the string contain "hello"?</button>
  <p id="result"></p>
  <script>
    const input = document.querySelector('#str');
    const checkBtn = document.querySelector('#check');
    const resultElm = document.querySelector('#result');
    const pattern = /hello/;

    checkBtn.addEventListener('click', function () {
      if (pattern.test(input.value)) {
        resultElm.textContent = 'Yes';
      } else {
        resultElm.textContent = 'No';
      }
    });
  </script>
</body>
</html>

常见例子

本节展示了一些如何使用 JavaScript 正则表达式匹配来测试常见用例的示例。应该注意的是,这里的正则表达式可能不是每种情况下的完美解决方案。它们每个都用于给出一个简单的示例来说明该过程的工作原理。

测试网址

您可以使用正则表达式测试字符串是否为 URL。您可以使用以下 CodePen 演示对此进行试验。

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
<meta charset="utf-8">
<style>
  .users {
    padding: 15px;
  }

  ul {
    margin-top: 15px;
  }
</style>
</head>
<body>
  <div>
    <label for="str">Enter a URL</label>
    <input type="text" name="str" id="str" />
  </div>
  <button id="check">Is the string a URL?</button>
  <p id="result"></p>
  <script>
    const input = document.querySelector('#str');
    const checkBtn = document.querySelector('#check');
    const resultElm = document.querySelector('#result');
    const pattern = /^(https?):\/\/[^\s$.?#].[^\s]*$/;

    checkBtn.addEventListener('click', function () {
      if (pattern.test(input.value)) {
        resultElm.textContent = 'Yes';
      } else {
        resultElm.textContent = 'No';
      }
    });
  </script>
</body>
</html>

请注意,上面使用的正则表达式模式要求 URL 以http://or开头https://

测试电子邮件

您可以使用正则表达式测试字符串是否为有效的电子邮件地址。以下 CodePen 演示展示了如何操作。

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
<meta charset="utf-8">
<style>
  .users {
    padding: 15px;
  }

  ul {
    margin-top: 15px;
  }
</style>
</head>
<body>
  <div>
    <label for="str">Enter string</label>
    <input type="text" name="str" id="str" />
  </div>
  <button id="check">Is this string an email?</button>
  <p id="result"></p>
  <script>
    const input = document.querySelector('#str');
    const checkBtn = document.querySelector('#check');
    const resultElm = document.querySelector('#result');
    const pattern = /^[a-zA-Z0–9+_.-]+@[a-zA-Z0–9.-]+$/;

    checkBtn.addEventListener('click', function () {
      if (pattern.test(input.value)) {
        resultElm.textContent = 'Yes';
      } else {
        resultElm.textContent = 'No';
      }
    });
  </script>
</body>
</html>

测试日期

您可以使用正则表达式测试字符串是否为日期。以下 CodePen 演示展示了它是如何完成的。

<!DOCTYPE html>
<html>
<head>
<title>Numbers</title>
<meta charset="utf-8">
<style>
  .users {
    padding: 15px;
  }

  ul {
    margin-top: 15px;
  }
</style>
</head>
<body>
  <div>
    <label for="str">Enter string</label>
    <input type="text" name="str" id="str" placeholder="DD-MM-YYYY"/>
  </div>
  <button id="check">Is this string a valid date?</button>
  <p id="result"></p>
  <script>
    const input = document.querySelector('#str');
    const checkBtn = document.querySelector('#check');
    const resultElm = document.querySelector('#result');
    const pattern = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;

    checkBtn.addEventListener('click', function () {
      if (pattern.test(input.value)) {
        resultElm.textContent = 'Yes';
      } else {
        resultElm.textContent = 'No';
      }
    });
  </script>
</body>
</html>

请注意,上面使用的正则表达式模式要求日期格式为“DD-MM-YYYY”或“DD/MM/YYYY”。

JavaScript 正则表达式匹配的其他方法

还有其他方法可以测试字符串是否与正则表达式匹配。本文并未涵盖所有内容,但这里是对它们的简要概述:

  • 匹配。此方法可用于字符串。它接受一个正则表达式作为参数,并检索与正则表达式匹配的字符串部分(如果有的话)。

  • 搜索。此方法可用于字符串。它接受一个正则表达式作为参数,搜索字符串中是否存在正则表达式模式,如果存在,则检索该模式在字符串中第一次出现的索引。

  • 执行。此方法可用于正则表达式。它接受一个字符串作为参数,在字符串中搜索正则表达式模式,如果有则检索结果。

结论

正则表达式对于测试字符串是否包含特定模式或子字符串非常有用。通过 JavaScript 正则表达式匹配,您可以检查字符串是否为 URL、日期、IP 地址或其他类型和格式。

与使用其他方法(如 )相比indexOf()test()正则表达式上可用的方法在测试字符串是否与模式匹配时为您提供了更大的灵活性。


您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://www.jiangweishan.com/article/js20221214a1.html

网友评论文明上网理性发言 已有0人参与

发表评论: