search
HomeWeb Front-endJS TutorialSummary of javascript regular expression definition (grammar)_javascript skills

This article talks about javascript regular expression definition (grammar). Share it with everyone for your reference, the details are as follows:

There are two ways to define regular expressions: one is to call RegExp() directly, and the second is to define it directly with literals, that is, var re = /regular rule/;

Both definition methods essentially call the RegExp() method

When calling the same regular code, the behavior in ECMAScript3 and ECMAScript5 is completely different

function reg(){
 var re = /\sjavascript/;
 return re;
}

分別在ECMAScript3和ECMAScript5中呼叫reg()方法多次

在ECMAScript3中,調用的是同一個RegExp對象,在ECMAScript5中,調用的是不同的RegExp對象 因為在EXCMAScript5中每執行一次,就生成一個新的RegExp對象

所以在ECMAScript3中會造成程式的隱患,因為只要在一個地方對這個物件進行修改的話,所有呼叫到這個物件的地方都會改變。

1.直接量字

在正規中一般都會直接匹配字符,如

/javascript/
會直接匹配字符javascript

也支援非字母的字元匹配,如:

o    NUL字元(u0000)

t    製表符(u0009)

n    換行符號(u000A)

v    垂直製表符(u000B)

f    換頁符(u000C)

r    回車符(u000D)

xnn   由十六進制數nn指定的拉丁字符,例如,x0A等價於

uxxxx 由十六進位數xxxx指定的Unicode字符,例如u0009等價於

cX   控製字元^X,例如,cJ等價於換行符n

在正規表示式中,還有一些有特殊意義的標點符號,他們需要''來轉義

^$.*+?=!:|/()[]{}

2.字元類別

[...]     方括號內的任一字元

[^...]    不在方括號內的任一字元

.        任一字元

w      任何ASCII字元組成的單字,等價於[a-zA-Z0-9]

W       任何不適ASCII字元組成的單詞,等價於[^a-zA-Z0-9]

s      任何Unicode空白符

S      任何非Unicode空白符的字符,並注意w和S不一樣

d      任何ASCII數值,等價於[0-9]

D      除了ASCII數字之外的任何字符,等價於[^0-9]

[b]     退格直接量(特例)

3.重複(次數)

?    0或1次

+    1次或多次

*    任次

{n}        n次

{m,n}     最少m次,最多n次

{n,}       n次或n次以上

正規預設是貪婪匹配的

如[a+b+]      若要符合aaabb,且它不會符合ab和aab等,只會符合aaabb

[a+?b+?]       這個會符合aaab   為什麼會產生這個差異呢?

答:+?是讓正則非貪婪匹配,那麼b這裡只會匹配一個b,那為什麼a會匹配3個呢?這是因為正規表示式的模式比對總是會尋找字串中第一個可能符合的位置。

4.選項|分組|引用

|  用於分隔可供選擇的字符,如[ab|cd],他既可以匹配ab也可以匹配cd,注意:選擇項的嘗試匹配次序是左→右,因此[a|ab],當a匹配通過了之後,就不匹配ab了,就算ab是更好的匹配

()  1.單獨的項當成子表達式    /java(script)?/     可將javascript與java   即圓括號部分形成子的表達式,可對子表達式執行| * ?

    2.完整的模式中定義子模式   後面的可以引用前面圓括號起來的表達式   /(['"])[a-z]1/     1引用的是第一個圓括號裡的表達式,因此引用了['"]

    3.後部引用前面的子表達式 

注意: /['"][a-z]['"]/這個正規的意思是     單引號或雙引號加上一個小寫字母加則加上一個單引號或雙引號,前後的單雙引號不是匹配的如果你要匹配可以這麼寫[(['"])[a-z]1]

加數字     可以引用前面圓括號中的表達式   

5.制定匹配位置(錨點)

^    符合字串的開頭,在多行檢索中,符合一行的開頭

$    符合字串的結尾,在多行檢索中,符合一行的結尾

b    符合一個單字的邊界,簡言之,就是位於字元w和W之間的位置,或位於字元w和字串的開頭或結尾之間的位置

B    符合非單字邊界的位置

(?=p)   零寬正向先行斷言,要求接下來的字元都與p匹配,但不能包括那些匹配p的字元

(?!p)  零寬負向先行斷言,要求接下來的字元不與p匹配

6.修飾符

寫在正規表示式字面量//右邊的

i        執行不區分大小寫的符合

g        執行一個全域匹配,簡言之,即找到所有的匹配,而不是在找到第一個之後就停止

m       多行配對模式,^符合一行的開頭與字串的開頭,$相符行的結束與字串的結束    /java$/m   可以符合  javanfunc

注意:當正規表示式是全域的時候,每次exec() 和test()的時候都會把目前設定的lastIndex設為目前的位置,再次執行的時候就會從lastIndex的位置開始執行,因此最好每次執行的時候lastIndex設定為0

希望本文所述對大家JavaScript程式設計有所幫助。

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool