python和JavaScript的正則表達(dá)式詳細(xì)使用對(duì)比
前言
?正則表達(dá)式在 Python 和 JavaScript 中都是一種強(qiáng)大的工具,用于匹配、搜索和操作字符串。盡管它們?cè)诨菊Z(yǔ)法上相似,但也存在一些差異。以下是 Python 和 JavaScript 在正則表達(dá)式的構(gòu)造和使用上的主要比較:
1 正則表達(dá)式的構(gòu)造和使用
特性 | Python | JavaScript |
---|---|---|
導(dǎo)入庫(kù) | 使用 re 模塊 | 無(wú)需導(dǎo)入,直接內(nèi)置 |
定義正則表達(dá)式 | re.compile(r"pattern") | /pattern/flags 或 new RegExp("pattern", "flags") |
匹配全部 | re.findall(pattern, string) | string.match(/pattern/g) 或 string.matchAll(/pattern/g) |
搜索(找到第一個(gè)匹配項(xiàng)) | re.search(pattern, string) | string.match(/pattern/) 或 string.search(/pattern/) |
替換 | re.sub(pattern, repl, string) | string.replace(/pattern/g, repl) |
分割字符串 | re.split(pattern, string) | string.split(/pattern/) |
忽略大小寫標(biāo)志 | re.IGNORECASE 或 'i' | 'i' |
多行匹配標(biāo)志 | re.MULTILINE 或 'm' | 'm' |
點(diǎn)號(hào)匹配任意字符(包括換行符) | re.DOTALL 或 's' | 無(wú)直接等價(jià),可使用[^]來(lái)匹配任意字符包括換行 |
Unicode匹配 | re.UNICODE 或 'u' | 使用'u'標(biāo)志 |
下面分別用 Python 和 JavaScript 的示例代碼展示正則表達(dá)式的常用操作,包括匹配、搜索、分割、替換、量詞、正向聲明、反向聲明、表達(dá)式分組和子表達(dá)式引用
import re text = "The quick brown fox jumps over the lazy dog 123. Windows 2000 and XP Windows. test test." # 匹配 match = re.search(r'\bfox\b', text) if match: print("Match found:", match.group()) # 輸出 'fox' # 搜索(使用量詞和表達(dá)式分組) search_result = re.findall(r'(\b\w{4}\b)', text) print("Search results:", search_result) # 輸出 ['quick', 'jumps', 'over', 'lazy'] # 分割 split_result = re.split(r'\s', text) print("Split results:", split_result) # 替換(使用子表達(dá)式引用) replace_result = re.sub(r'(\w+) (\w+)', r'\2 \1', text) print("Replace results:", replace_result) # 正向和反向聲明(Lookahead and Lookbehind) lookahead = re.search(r'Windows(?= 2000)', text) if lookahead: print("Lookahead found:", lookahead.group()) # 輸出 'Windows' lookbehind = re.search(r'(?<=XP )Windows', text) if lookbehind: print("Lookbehind found:", lookbehind.group()) # 輸出 'Windows' # 子表達(dá)式引用 repeat_word = re.search(r'(\b\w+\b) \1', text) if repeat_word: print("Repeat word found:", repeat_word.group()) # 輸出 'test test' # 表達(dá)式分組使用 grouped = re.search(r'(\b\w+\b) over the (\b\w+\b)', text) if grouped: print("Words over:", grouped.groups()) # 輸出 ('jumps', 'lazy')
let text = "The quick brown fox jumps over the lazy dog 123. Windows 2000 and XP Windows. test test."; // 匹配 let match = text.match(/fox/); if (match) { console.log("Match found:", match[0]); // 輸出 'fox' } // 搜索(使用量詞和表達(dá)式分組) let searchResult = text.match(/\b\w{4}\b/g); console.log("Search results:", searchResult); // 輸出 ['quick', 'jumps', 'over', 'lazy'] // 分割 let splitResult = text.split(/\s/); console.log("Split results:", splitResult); // 替換(使用子表達(dá)式引用) let replaceResult = text.replace(/(\w+) (\w+)/g, '$2 $1'); console.log("Replace results:", replaceResult); // 正向和反向聲明(Lookahead and Lookbehind) let lookahead = text.match(/Windows(?= 2000)/); if (lookahead) { console.log("Lookahead found:", lookahead[0]); // 輸出 'Windows' } let lookbehind = text.match(/(?<=XP )Windows/); if (lookbehind) { console.log("Lookbehind found:", lookbehind[0]); // 輸出 'Windows' // 子表達(dá)式引用 let repeatWord = text.match(/(\b\w+\b) \1/); if (repeatWord) { console.log("Repeat word found:", repeatWord[0]); // 輸出 'test test' } // 表達(dá)式分組使用 let grouped = text.match(/(\b\w+\b) over the (\b\w+\b)/); if (grouped) { console.log("Words over:", grouped[1], grouped[2]); // 輸出 'jumps', 'lazy' }
2 正則表達(dá)式的實(shí)例方法(僅JavaScript有)
2.1. exec()
描述: 執(zhí)行對(duì)字符串的搜索匹配,并返回一個(gè)結(jié)果數(shù)組或 null。如果正則表達(dá)式包含了全局標(biāo)志 (g),每次調(diào)用 exec() 將從正則表達(dá)式的 lastIndex 屬性指定的位置開(kāi)始搜索下一個(gè)匹配。
返回值: 返回一個(gè)數(shù)組,其中第 0 個(gè)元素是匹配的完整字符串,后續(xù)元素是匹配的捕獲組(如果有)。如果沒(méi)有找到匹配,則返回 null。
示例:
const regex = /(\w+)\s/g; const text = "hello world"; let match; while ((match = regex.exec(text)) !== null) { console.log(`Found ${match[0]}, next starts at ${regex.lastIndex}.`); // 輸出: Found hello , next starts at 6 // Found world, next starts at 11 }
2.2. test()
描述: 測(cè)試字符串是否匹配正則表達(dá)式的模式。
返回值: 如果找到匹配則返回 true,否則返回 false。
示例:
const regex = /hello/; const text = "hello world"; const result = regex.test(text); // 返回 true console.log(result);
2.3. compile()
描述: 重新編譯正則表達(dá)式。建議避免使用它,直接創(chuàng)建新的正則表達(dá)式實(shí)例更為合適和安全。
3 正則表達(dá)式的屬性(僅JavaScript有)
3.1 實(shí)例屬性
實(shí)例屬性是綁定到正則表達(dá)式實(shí)例上的屬性。它們提供有關(guān)特定正則表達(dá)式對(duì)象的信息,每個(gè)實(shí)例的這些屬性都是獨(dú)立的。常見(jiàn)的實(shí)例屬性包括:
source:
- 描述:正則表達(dá)式的源文本字符串。
- 用途:允許查看創(chuàng)建正則表達(dá)式時(shí)使用的確切模式。
flags:
- 描述:標(biāo)明正則表達(dá)式使用的修飾符(如
g
,i
,m
等)。 - 用途:快速查看正則表達(dá)式對(duì)象應(yīng)用的全局規(guī)則和配置。
- 描述:標(biāo)明正則表達(dá)式使用的修飾符(如
lastIndex:
- 描述:下一次匹配開(kāi)始的字符位置,僅在正則表達(dá)式使用全局標(biāo)志
g
或粘連標(biāo)志y
時(shí)有效。 - 用途:在進(jìn)行多次匹配時(shí),控制或查詢下次匹配的起始位置。
- 描述:下一次匹配開(kāi)始的字符位置,僅在正則表達(dá)式使用全局標(biāo)志
global, ignoreCase, multiline, dotAll, unicode, sticky:
- 描述:這些布爾值屬性反映了相應(yīng)的修飾符是否被應(yīng)用于正則表達(dá)式。
- 用途:提供對(duì)正則表達(dá)式行為詳細(xì)了解的快速方式。
// 定義一個(gè)正則表達(dá)式對(duì)象,包含多個(gè)修飾符 let regex = new RegExp('foo', 'gim'); // 實(shí)例屬性 console.log("Source:", regex.source); // 輸出: foo console.log("Flags:", regex.flags); // 輸出: gim console.log("Global:", regex.global); // 輸出: true console.log("Ignore Case:", regex.ignoreCase); // 輸出: true console.log("Multiline:", regex.multiline); // 輸出: true // 使用正則表達(dá)式進(jìn)行匹配 let text = "Foo bar foo"; let match; while ((match = regex.exec(text)) !== null) { console.log(`Found '${match[0]}' at index ${match.index}`); console.log("LastIndex after match:", regex.lastIndex); // 顯示匹配后的 lastIndex }
3.2 靜態(tài)屬性
靜態(tài)屬性與特定的 RegExp
對(duì)象無(wú)關(guān),而是與 RegExp
構(gòu)造函數(shù)本身關(guān)聯(lián)。這些屬性主要用于存儲(chǔ)有關(guān)最近一次正則表達(dá)式操作的全局信息。靜態(tài)屬性的值會(huì)在正則表達(dá)式操作后更新,并且可以在不同的匹配和搜索操作之間共享。常見(jiàn)的靜態(tài)屬性包括:
RegExp.input (
$_
):- 描述:存儲(chǔ)最近一次被匹配的完整字符串。
- 用途:可以快速查看或再次處理上一次匹配的字符串。
RegExp.lastMatch (
$&
):- 描述:存儲(chǔ)最近一次成功匹配的整個(gè)字符串。
- 用途:用于引用上一次匹配的結(jié)果。
RegExp.lastParen (
$+
):- 描述:存儲(chǔ)最近一次匹配的最后一個(gè)捕獲組。
- 用途:在需要?jiǎng)討B(tài)訪問(wèn)最后一個(gè)捕獲組時(shí)非常有用。
RegExp.leftContext (
$```) 和 **RegExp.rightContext** (
$'`):- 描述:分別存儲(chǔ)在最近一次匹配之前和之后的字符串部分。
- 用途:允許訪問(wèn)與匹配相關(guān)的上下文信息。
RegExp.$1 到 RegExp.$9:
- 描述:存儲(chǔ)最近一次匹配的第1到第9個(gè)捕獲組。
- 用途:快速訪問(wèn)最近一次匹配中的特定捕獲組。
let text = "Example text with 'term' and another 'term'."; let regex = /'term'/g; // 全局搜索 'term' // 進(jìn)行匹配 regex.exec(text); regex.exec(text); // 靜態(tài)屬性 console.log("Last Match:", RegExp.lastMatch); // 輸出: 'term' console.log("Last Paren:", RegExp.lastParen); // 輸出: '', 沒(méi)有捕獲組 console.log("Left Context:", RegExp.leftContext); // 輸出: Example text with 'term' and another console.log("Right Context:", RegExp.rightContext); // 輸出: '. // 匹配多次后檢查靜態(tài)屬性 console.log("Input:", RegExp.input); // 輸出: Example text with 'term' and another 'term'.
總結(jié)
到此這篇關(guān)于python和JavaScript的正則表達(dá)式詳細(xì)使用對(duì)比的文章就介紹到這了,更多相關(guān)python和JS正則表達(dá)式對(duì)比內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python使用execute_script模擬鼠標(biāo)滾動(dòng)、鼠標(biāo)點(diǎn)擊等示例
- Python調(diào)用JavaScript代碼的幾種方法小結(jié)
- Python報(bào)錯(cuò)TypeError: ‘NoneType‘ object is not subscriptable的解決方法匯總
- Python報(bào)錯(cuò):TypeError:?‘xxx‘?object?is?not?subscriptable解決辦法
- Python成功解決TypeError: ‘method’ object is not subscriptable
- python如何提取script的部分內(nèi)容
相關(guān)文章
JavaScript正則表達(dá)式校驗(yàn)非負(fù)整數(shù)實(shí)例
本文分享了JavaScript正則表達(dá)式(^\d+$ 或 ^[1-9]\d*|0$)校驗(yàn)非負(fù)整數(shù)實(shí)例代碼,代碼簡(jiǎn)單易懂,需要的朋友可以看下2016-12-12JavaScript正則表達(dá)式驗(yàn)證中文實(shí)例講解
JavaScript經(jīng)常會(huì)驗(yàn)證中文本文將提供使用正則表達(dá)式實(shí)現(xiàn),接下來(lái)介紹兩個(gè)實(shí)例,感興趣的你可不要錯(cuò)過(guò)了哈,希望本例知識(shí)點(diǎn)可以幫助到你2013-02-02正則表達(dá)式re.sub替換不完整的問(wèn)題及完整解決方案
re.sub是個(gè)正則表達(dá)式方面的函數(shù),用來(lái)實(shí)現(xiàn)通過(guò)正則表達(dá)式,實(shí)現(xiàn)比普通字符串的replace更加強(qiáng)大的替換功能。這篇文章主要介紹了正則表達(dá)式re.sub替換不完整的問(wèn)題及解決方案,需要的朋友可以參考下2018-08-08javascript 手機(jī)號(hào)碼正則表達(dá)式驗(yàn)證函數(shù)
隨著手機(jī)號(hào)碼段的不斷增加,以前網(wǎng)上的手機(jī)號(hào)碼驗(yàn)證函數(shù)都不能那么完美的支持了,這里腳本之家編輯特為大家準(zhǔn)備的一個(gè)簡(jiǎn)單的正則與手機(jī)驗(yàn)證的函數(shù)分析。2009-12-12正則驗(yàn)證不能含有中文的實(shí)現(xiàn)方法【jQuery與java實(shí)現(xiàn)】
這篇文章主要介紹了正則驗(yàn)證不能含有中文的實(shí)現(xiàn)方法,結(jié)合jQuery與java兩種實(shí)現(xiàn)方法分析了針對(duì)中文的正則驗(yàn)證操作技巧,需要的朋友可以參考下2017-01-01JS 正則表達(dá)式中小括號(hào)的應(yīng)用
在正則表達(dá)式中小括號(hào)的應(yīng)用種類比較多,差別也很大2009-12-12