使用 JavaScript 的正则表达式使用 JavaScript 的正则表达式使用 JavaScript 的正则表达式使用 JavaScript 的正则表达式
  • 文章
  • 正则表达式
    • 工具
  • 登录
找到的结果: {phrase} (显示: {results_count} 共: {results_count_total})
显示: {results_count} 共: {results_count_total}

加载更多搜索结果...

搜索范围
模糊匹配
搜索标题
搜索内容
发表 admin at 2024年3月5日
类别
  • 正则表达式
标签
使用 JavaScript 的正则表达式
  • 简
  • 繁
  • En
关于正则表达式 » 正则表达式工具和实用程序 » 使用 JavaScript 的正则表达式

正则表达式工具
grep
语言与程序库
Boost
Delphi
GNU (Linux)
Groovy
Java
JavaScript
.NET
PCRE (C/C++)
PCRE2 (C/C++)
Perl
PHP
POSIX
PowerShell
Python
R
Ruby
std::regex
Tcl
VBScript
Visual Basic 6
wxWidgets
XML Schema
Xojo
XQuery 与 XPath
XRegExp
数据库
MySQL
Oracle
PostgreSQL
本网站的更多内容
简介
正则表达式快速入门
正则表达式教程
替换字符串教程
应用程序与语言
正则表达式范例
正则表达式参考
替换字符串参考

使用 JavaScript 的正则表达式

JavaScript 的正则表达式风格是 ECMA-262 语言标准的一部分。这表示您的正则表达式应可在所有 JavaScript 实作中以完全相同的方式运作。过去有许多严重的浏览器特定问题。但现代浏览器在遵循正则表达式的 JavaScript 标准方面做得很好。您只需要确定您的网页具有请求浏览器使用标准模式而非奇异模式的 DOCTYPE。

JavaScript 的正则表达式风格

在 JavaScript 原代码中,正则表达式以 /pattern/modifiers 的形式撰写,其中「pattern」是正则表达式本身,而「modifiers」是一系列表示各种选项的字符。「modifiers」部分是选用的。此语法取自 Perl。JavaScript 支持下列 modifiers,这是 Perl 支持的子集

  • /g 激活「全域」比对。使用 replace() 方法时,指定此 modifiers 以取代所有比对,而不仅仅是第一个。
  • /i 使正则表达式比对不区分大小写。
  • /m 激活「多行模式」。在此模式中,插入符号和美元符号会比对主旨字符串中换行符号的前后。
  • /s 激活「单行模式」。在此模式中,句点会比对换行符号。此 modifiers 在 ECMAScript 2018 中添加。较旧的浏览器,包括 Internet Explorer 和原始 Edge,不支持它。

您可以通过将多个 modifiers 串接在一起的方式来结合它们,例如 /regex/gim。值得注意的是,没有选项可以 让句点比对换行符号字符。

由于正斜线用于分隔正则表达式,因此出现在正则表达式中的任何正斜线都需要进行转义。例如,正则表达式 1/2 在 JavaScript 中写作 /1\/2/。

若要匹配不含 /s 的绝对任何字符,可以使用包含 字符类别 和其否定版本(例如 [\s\S])的 简写类别。

JavaScript 实作 Perl 风格的正则表达式。然而,它缺少 Perl 和其他现代正则表达式风格中相当多的高端功能。

  • 没有 \A 或 \Z锚点 来匹配字符串的开头或结尾。请改用 插入符号或美元符号。
  • 没有 原子组 或 占有量词。
  • 没有 Unicode 支持,但可以通过 \uFFFF 匹配单一字符。
  • 没有 命名捕获组。请改用 编号捕获组。
  • 没有 模式修改器 来设置正则表达式中的匹配选项。
  • 没有 条件。
  • 没有 正则表达式注解。请改用 JavaScript // 注解来描述正则表达式,并置于正则表达式字符串之外。

这些功能中的许多功能都可以在 JavaScript 的 XRegExp 函数库 中找到。

  • 后向参考 在很长一段时间内都是 JavaScript 正则表达式语法中的重大遗漏。后向参考是 ECMAScript 2018 规范的一部分。它受到最新版本的 Chrome、Edge 和 Firefox 支持,但不受 Internet Explorer 等旧浏览器支持。
  • 字符串类别的正则表达式方法

    若要测试特定正则表达式是否匹配(部分)字符串,可以调用字符串的 match() 方法:if (myString.match(/regex/)) { /*Success!*/ }。如果您想验证用户输入,您应该使用 锚点 来确保您正在针对整个字符串进行测试。若要测试用户是否输入数字,请使用:myString.match(/^\d+$/)。 /\d+/ 匹配任何包含一个或多个数字的字符串,但 /^\d+$/ 仅匹配完全由数字组成的字符串。

    若要使用正则表达式进行搜索和取代,请使用字符串的 replace() 方法:myString.replace(/replaceme/g, "replacement")。使用 /g 修饰词可确保取代「replaceme」的所有出现。第二个参数是一个包含取代文本的常规字符串。

    使用字符串的 split() 方法允许您使用正则表达式将字符串分割成字符串数组,以确定字符串被分割的位置。例如,myArray = myString.split(/,/) 将逗号分隔的清单分割成数组。逗号本身不包含在产生的字符串数组中。

    如何使用 JavaScript RegExp 对象

    创建新 RegExp 对象最简单的方式就是使用特殊的 regex 语法:myregexp = /regex/。如果正则表达式在字符串中(例如用户输入),可以使用 RegExp 构造函数:myregexp = new RegExp(regexstring)。修饰词可以指定为第二个参数:myregexp = new RegExp(regexstring, "gim")。

    建议不要对文本字符串使用 RegExp 构造函数,因为在文本字符串中,反斜线必须加上转义字符。正则表达式 \w+ 可以创建为 re = /\w+/ 或 re = new RegExp("\\w+")。后者绝对比较难读。正则表达式 \\ 符合单一反斜线。在 JavaScript 中,这会变成 re = /\\/ 或 re = new RegExp("\\\\")。

    不论用哪种方式创建「myregexp」,都可以传递给上面说明的 String 方法,而不是文本正则表达式:myString.replace(myregexp, "replacement")。

    如果您想要截取符合字符串的部分,请调用您创建的 RegExp 对象的 exec() 函数,例如:mymatch = myregexp.exec("subject")。此函数会传回数组。数组中的第零个项目会保留符合正则表达式的文本。后面的项目会包含符合 regexp 中 截取括号 的文本(如果有的话)。mymatch.length 表示 match[] 数组的长度,比正则表达式中的捕获组数量多一个。mymatch.index 表示正则表达式符合的主题字符串中的字符位置。mymatch.input 会保留主题字符串的副本。

    调用 exec() 函数也会变更 RegExp 对象的 lastIndex 属性。它会保存主题字符串中下一次符合尝试会开始的索引。您可以修改此值,以变更下一次调用 exec() 的起始位置。

    RegExp 对象的 test() 函数是 exec() != null 的捷径。它会将主题字符串视为参数,并根据 regex 是否符合字符串的一部分,传回 true 或 false。

    您也可以对文本正则表达式调用这些方法。/\d/.test(subject) 是快速测试主题字符串中是否有数字的方法。

    替换文本语法

    String.replace() 函数会诠释替换文本字符串中的几个占位符。如果 regexp 包含 捕获组,您可以在替换文本中使用 反向引用。$1 在替换文本中会插入符合第一个捕获组的文本,$2 是第二个,以此类推,直到 $99。如果您的 regex 有 1 个以上但少于 10 个捕获组,那么 $10 会视为对第一个群组的反向引用,后面接着文本 0。如果您的 regex 有少于 7 个捕获组,那么 $7 会视为文本 $7。$& 会重新插入整个 regex 符合项。$`(反引号)会插入 regex 符合项左边的文本,$'(单引号)会插入 regex 符合项右边的文本。$$ 会插入单一美元符号,任何未形成此处说明的占位符之一的 $ 也是如此。

    $_ 和 $+ 虽然不是标准的一部分,但仍受到一些浏览器的支持。在 Internet Explorer 中,$_ 会插入整个主旨字符串。在 Internet Explorer 和 Firefox 中,$+ 会插入与正则表达式中编号最高的捕获组相符的文本。如果编号最高的群组没有参与比对,$+ 会被替换为空白。这与 Perl 中的 $+ 不同,后者会插入与实际参与比对的编号最高的捕获组相符的文本。

    虽然像 $& 之类的东西在 Perl 中实际上是可以在任何地方运作的变量,但在 JavaScript 中,它们只存在于传递给 replace() 函数的替换字符串中的占位符。

    在您的网络浏览器中测试 JavaScript 的 RegExp 支持

    我创建了一个 范例网页,展示 JavaScript 的正则表达式支持 的实际运作。您现在可以在您的网络浏览器中试用看看。原代码显示在范例下方。

    使用 JavaScript 的正規表示式
    • 简
    • 繁
    • En
    關於正規表示式 » 正規表示式工具和實用程式 » 使用 JavaScript 的正規表示式

    正規表示式工具
    grep
    語言與程式庫
    Boost
    Delphi
    GNU (Linux)
    Groovy
    Java
    JavaScript
    .NET
    PCRE (C/C++)
    PCRE2 (C/C++)
    Perl
    PHP
    POSIX
    PowerShell
    Python
    R
    Ruby
    std::regex
    Tcl
    VBScript
    Visual Basic 6
    wxWidgets
    XML Schema
    Xojo
    XQuery 與 XPath
    XRegExp
    資料庫
    MySQL
    Oracle
    PostgreSQL
    本網站的更多內容
    簡介
    正規表示式快速入門
    正規表示式教學
    替換字串教學
    應用程式與語言
    正規表示式範例
    正規表示式參考
    替換字串參考

    使用 JavaScript 的正規表示式

    JavaScript 的正規表示式風格是 ECMA-262 語言標準的一部分。這表示您的正規表示式應可在所有 JavaScript 實作中以完全相同的方式運作。過去有許多嚴重的瀏覽器特定問題。但現代瀏覽器在遵循正規表示式的 JavaScript 標準方面做得很好。您只需要確定您的網頁具有請求瀏覽器使用標準模式而非奇異模式的 DOCTYPE。

    JavaScript 的正規表示式風格

    在 JavaScript 原始碼中,正規表示式以 /pattern/modifiers 的形式撰寫,其中「pattern」是正規表示式本身,而「modifiers」是一系列表示各種選項的字元。「modifiers」部分是選用的。此語法取自 Perl。JavaScript 支援下列 modifiers,這是 Perl 支援的子集

    • /g 啟用「全域」比對。使用 replace() 方法時,指定此 modifiers 以取代所有比對,而不仅仅是第一個。
    • /i 使正規表示式比對不區分大小寫。
    • /m 啟用「多行模式」。在此模式中,插入符號和美元符號會比對主旨字串中換行符號的前後。
    • /s 啟用「單行模式」。在此模式中,句點會比對換行符號。此 modifiers 在 ECMAScript 2018 中新增。較舊的瀏覽器,包括 Internet Explorer 和原始 Edge,不支援它。

    您可以透過將多個 modifiers 串接在一起的方式來結合它們,例如 /regex/gim。值得注意的是,沒有選項可以 讓句點比對換行符號字元。

    由於正斜線用於分隔正規表示式,因此出現在正規表示式中的任何正斜線都需要進行跳脫。例如,正規表示式 1/2 在 JavaScript 中寫作 /1\/2/。

    若要匹配不含 /s 的絕對任何字元,可以使用包含 字元類別 和其否定版本(例如 [\s\S])的 簡寫類別。

    JavaScript 實作 Perl 風格的正規表示式。然而,它缺少 Perl 和其他現代正規表示式風格中相當多的進階功能。

    • 沒有 \A 或 \Z錨點 來匹配字串的開頭或結尾。請改用 插入符號或美元符號。
    • 沒有 原子群組 或 佔有量詞。
    • 沒有 Unicode 支援,但可以透過 \uFFFF 匹配單一字元。
    • 沒有 命名擷取群組。請改用 編號擷取群組。
    • 沒有 模式修改器 來設定正規表示式中的匹配選項。
    • 沒有 條件。
    • 沒有 正規表示式註解。請改用 JavaScript // 註解來描述正規表示式,並置於正規表示式字串之外。

    這些功能中的許多功能都可以在 JavaScript 的 XRegExp 函式庫 中找到。

  • 後向參考 在很長一段時間內都是 JavaScript 正規表示式語法中的重大遺漏。後向參考是 ECMAScript 2018 規範的一部分。它受到最新版本的 Chrome、Edge 和 Firefox 支援,但不受 Internet Explorer 等舊瀏覽器支援。
  • 字串類別的正規表示式方法

    若要測試特定正規表示式是否匹配(部分)字串,可以呼叫字串的 match() 方法:if (myString.match(/regex/)) { /*Success!*/ }。如果您想驗證使用者輸入,您應該使用 錨點 來確保您正在針對整個字串進行測試。若要測試使用者是否輸入數字,請使用:myString.match(/^\d+$/)。 /\d+/ 匹配任何包含一個或多個數字的字串,但 /^\d+$/ 僅匹配完全由數字組成的字串。

    若要使用正規表示式進行搜尋和取代,請使用字串的 replace() 方法:myString.replace(/replaceme/g, "replacement")。使用 /g 修飾詞可確保取代「replaceme」的所有出現。第二個參數是一個包含取代文字的常規字串。

    使用字串的 split() 方法允許您使用正規表示式將字串分割成字串陣列,以確定字串被分割的位置。例如,myArray = myString.split(/,/) 將逗號分隔的清單分割成陣列。逗號本身不包含在產生的字串陣列中。

    如何使用 JavaScript RegExp 物件

    建立新 RegExp 物件最簡單的方式就是使用特殊的 regex 語法:myregexp = /regex/。如果正規表示式在字串中(例如使用者輸入),可以使用 RegExp 建構函式:myregexp = new RegExp(regexstring)。修飾詞可以指定為第二個參數:myregexp = new RegExp(regexstring, "gim")。

    建議不要對文字字串使用 RegExp 建構函式,因為在文字字串中,反斜線必須加上跳脫字元。正規表示式 \w+ 可以建立為 re = /\w+/ 或 re = new RegExp("\\w+")。後者絕對比較難讀。正規表示式 \\ 符合單一反斜線。在 JavaScript 中,這會變成 re = /\\/ 或 re = new RegExp("\\\\")。

    不論用哪種方式建立「myregexp」,都可以傳遞給上面說明的 String 方法,而不是文字正規表示式:myString.replace(myregexp, "replacement")。

    如果您想要擷取符合字串的部分,請呼叫您建立的 RegExp 物件的 exec() 函式,例如:mymatch = myregexp.exec("subject")。此函式會傳回陣列。陣列中的第零個項目會保留符合正規表示式的文字。後面的項目會包含符合 regexp 中 擷取括號 的文字(如果有的話)。mymatch.length 表示 match[] 陣列的長度,比正規表示式中的擷取群組數量多一個。mymatch.index 表示正規表示式符合的主題字串中的字元位置。mymatch.input 會保留主題字串的副本。

    呼叫 exec() 函式也會變更 RegExp 物件的 lastIndex 屬性。它會儲存主題字串中下一次符合嘗試會開始的索引。您可以修改此值,以變更下一次呼叫 exec() 的起始位置。

    RegExp 物件的 test() 函式是 exec() != null 的捷徑。它會將主題字串視為參數,並根據 regex 是否符合字串的一部分,傳回 true 或 false。

    您也可以對文字正規表示式呼叫這些方法。/\d/.test(subject) 是快速測試主題字串中是否有數字的方法。

    替換文字語法

    String.replace() 函式會詮釋替換文字字串中的幾個佔位符。如果 regexp 包含 擷取群組,您可以在替換文字中使用 反向參照。$1 在替換文字中會插入符合第一個擷取群組的文字,$2 是第二個,以此類推,直到 $99。如果您的 regex 有 1 個以上但少於 10 個擷取群組,那麼 $10 會視為對第一個群組的反向參照,後面接著文字 0。如果您的 regex 有少於 7 個擷取群組,那麼 $7 會視為文字 $7。$& 會重新插入整個 regex 符合項。$`(反引號)會插入 regex 符合項左邊的文字,$'(單引號)會插入 regex 符合項右邊的文字。$$ 會插入單一美元符號,任何未形成此處說明的佔位符之一的 $ 也是如此。

    $_ 和 $+ 雖然不是標準的一部分,但仍受到一些瀏覽器的支援。在 Internet Explorer 中,$_ 會插入整個主旨字串。在 Internet Explorer 和 Firefox 中,$+ 會插入與正規表示式中編號最高的擷取群組相符的文字。如果編號最高的群組沒有參與比對,$+ 會被替換為空白。這與 Perl 中的 $+ 不同,後者會插入與實際參與比對的編號最高的擷取群組相符的文字。

    雖然像 $& 之類的東西在 Perl 中實際上是可以在任何地方運作的變數,但在 JavaScript 中,它們只存在於傳遞給 replace() 函式的替換字串中的佔位符。

    在您的網路瀏覽器中測試 JavaScript 的 RegExp 支援

    我建立了一個 範例網頁,展示 JavaScript 的正規表示式支援 的實際運作。您現在可以在您的網路瀏覽器中試用看看。原始碼顯示在範例下方。

    Using Regular Expressions with JavaScript
    • 简
    • 繁
    • En
    About Regular Expressions » Tools and Utilities for Regular Expressions » Using Regular Expressions with JavaScript

    Regex Tools
    grep
    Languages & Libraries
    Boost
    Delphi
    GNU (Linux)
    Groovy
    Java
    JavaScript
    .NET
    PCRE (C/C++)
    PCRE2 (C/C++)
    Perl
    PHP
    POSIX
    PowerShell
    Python
    R
    Ruby
    std::regex
    Tcl
    VBScript
    Visual Basic 6
    wxWidgets
    XML Schema
    Xojo
    XQuery & XPath
    XRegExp
    Databases
    MySQL
    Oracle
    PostgreSQL
    More on This Site
    Introduction
    Regular Expressions Quick Start
    Regular Expressions Tutorial
    Replacement Strings Tutorial
    Applications and Languages
    Regular Expressions Examples
    Regular Expressions Reference
    Replacement Strings Reference

    Using Regular Expressions with JavaScript

    JavaScript’s regular expression flavor is part of the ECMA-262 standard for the language. This means your regular expressions should work exactly the same in all implementations of JavaScript. In the past there were many serious browser-specific issues. But modern browsers do a very good job of following the JavaScript standard for regular expressions. You only need to make sure your web pages have a doctype that requests the browser to use standards mode rather than quirks mode.

    JavaScript’s Regular Expression Flavor

    In JavaScript source code, a regular expression is written in the form of /pattern/modifiers where “pattern” is the regular expression itself, and “modifiers” are a series of characters indicating various options. The “modifiers” part is optional. This syntax is borrowed from Perl. JavaScript supports the following modifiers, a subset of those supported by Perl:

    • /g enables “global” matching. When using the replace() method, specify this modifier to replace all matches, rather than only the first one.
    • /i makes the regex match case insensitive.
    • /m enables “multi-line mode”. In this mode, the caret and dollar match before and after line breaks in the subject string.
    • /s enables “single-line mode”. In this mode, the dot matches line breaks. This modifier is new in ECMAScript 2018. Older browsers, including Internet Explorer and the original Edge, do not support it.

    You can combine multiple modifiers by stringing them together as in /regex/gim. Notably absent is an option to make the dot match line break characters.

    Since forward slashes delimit the regular expression, any forward slashes that appear in the regex need to be escaped. E.g. the regex 1/2 is written as /1\/2/ in JavaScript.

    To match absolutely any character without /s, you can use character class that contains a shorthand class and its negated version, such as [\s\S].

    JavaScript implements Perl-style regular expressions. However, it lacks quite a number of advanced features available in Perl and other modern regular expression flavors:

    • No \A or \Z anchors to match the start or end of the string. Use a caret or dollar instead.
    • No atomic grouping or possessive quantifiers.
    • No Unicode support, except for matching single characters with \uFFFF.
    • No named capturing groups. Use numbered capturing groups instead.
    • No mode modifiers to set matching options within the regular expression.
    • No conditionals.
    • No regular expression comments. Describe your regular expression with JavaScript // comments instead, outside the regular expression string.

    Many of these features are available in the XRegExp library for JavaScript.

  • Lookbehind was a major omission in JavaScript’s regex syntax for the longest time. Lookbehind is part of the ECMAScript 2018 specification. It is supported by the latest versions of Chrome, Edge, and Firefox but not by older browsers such as Internet Explorer.
  • Regexp Methods of The String Class

    To test if a particular regex matches (part of) a string, you can call the strings’s match() method: if (myString.match(/regex/)) { /*Success!*/ }. If you want to verify user input, you should use anchors to make sure that you are testing against the entire string. To test if the user entered a number, use: myString.match(/^\d+$/). /\d+/ matches any string containing one or more digits, but /^\d+$/ matches only strings consisting entirely of digits.

    To do a search and replace with regexes, use the string’s replace() method: myString.replace(/replaceme/g, "replacement"). Using the /g modifier makes sure that all occurrences of “replaceme” are replaced. The second parameter is an normal string with the replacement text.

    Using a string’s split() method allows you to split the string into an array of strings using a regular expression to determine the positions at which the string is splitted. E.g. myArray = myString.split(/,/) splits a comma-delimited list into an array. The comma’s themselves are not included in the resulting array of strings.

    How to Use The JavaScript RegExp Object

    The easiest way to create a new RegExp object is to simply use the special regex syntax: myregexp = /regex/. If you have the regular expression in a string (e.g. because it was typed in by the user), you can use the RegExp constructor: myregexp = new RegExp(regexstring). Modifiers can be specified as a second parameter: myregexp = new RegExp(regexstring, "gim").

    I recommend that you do not use the RegExp constructor with a literal string, because in literal strings, backslashes must be escaped. The regular expression \w+ can be created as re = /\w+/ or as re = new RegExp("\\w+"). The latter is definitely harder to read. The regular expression \\ matches a single backslash. In JavaScript, this becomes re = /\\/ or re = new RegExp("\\\\").

    Whichever way you create “myregexp”, you can pass it to the String methods explained above instead of a literal regular expression: myString.replace(myregexp, "replacement").

    If you want to retrieve the part of the string that was matched, call the exec() function of the RegExp object that you created, e.g.: mymatch = myregexp.exec("subject"). This function returns an array. The zeroth item in the array will hold the text that was matched by the regular expression. The following items contain the text matched by the capturing parentheses in the regexp, if any. mymatch.length indicates the length of the match[] array, which is one more than the number of capturing groups in your regular expression. mymatch.index indicates the character position in the subject string at which the regular expression matched. mymatch.input keeps a copy of the subject string.

    Calling the exec() function also changes the lastIndex property of the RegExp object. It stores the index in the subject string at which the next match attempt will begin. You can modify this value to change the starting position of the next call to exec().

    The test() function of the RegExp object is a shortcut to exec() != null. It takes the subject string as a paarameter and returns true or false depending on whether the regex matches part of the string or not.

    You can call these methods on literal regular expressions too. /\d/.test(subject) is a quick way to test whether there are any digits in the subject string.

    Replacement Text Syntax

    The String.replace() function interprets several placeholders in the replacement text string. If the regexp contains capturing groups, you can use backreferences in the replacement text. $1 in the replacement text inserts the text matched by the first capturing group, $2 the second, and so on until $99. If your regex has more than 1 but fewer than 10 capturing groups, then $10 is treated as a backreference to the first group followed by a literal zero. If your regex has fewer than 7 capturing groups, then $7 is treated as the literal text $7. $& reinserts the whole regex match. $` (backtick) inserts the text to the left of the regex match, $' (single quote) inserts the text to the right of the regex match. $$ inserts a single dollar sign, as does any $ that does not form one of the placeholders described here.

    $_ and $+ are not part of the standard but are supported by some browsers nonetheless. In Internet Explorer, $_ inserts the entire subject string. In Internet Explorer and Firefox, $+ inserts the text matched by the highest-numbered capturing group in the regex. If the highest-numbered group did not participate in the match, $+ is replaced with nothing. This is not the same as $+ in Perl, which inserts the text matched by the highest-numbered capturing group that actually participated in the match.

    While things like $& are actually variables in Perl that work anywhere, in JavaScript these only exist as placeholders in the replacement string passed to the replace() function.

    Test JavaScript’s RegExp Support In Your Web Browser

    I have created an example web page showing JavaScript’s regex support in action. You can try it right now in your web browser. Source code is displayed below the example.

    ©2015-2025 艾丽卡 support@alaica.com