search
HomeWeb Front-endJS TutorialRegular expressions (grammar)

Regular expressions (grammar)

May 21, 2018 am 09:35 AM
regularexpressiongrammar

Now I will bring you a regular expression (grammar recommendation). Let me share it with you now and give it as a reference for everyone.

Construction summary of regular expression

Construction matches

Character

x Character x
\\ Backslash character
\0n Character n with octal value 0 (0 \0nn Character nn with octal value 0 (0 \0mnn character mnn with octal value 0 (0 \xhh with hexadecimal value Character hh with value 0x
\uhhhh Character hhhh with hexadecimal value 0x
\t Tab character ('\u0009')
\n Newline (newline) character ('\u000A ')
\r Carriage return character ('\u000D')
\f Form feed character ('\u000C')
\a Alarm (bell) character ('\u0007')
\ e escape character ('\u001B')
\cx Control character corresponding to x

Character class

[abc] a, b or c ( Simple class)
[^abc] Any character except a, b or c (negative)
[a-zA-Z] a to z or A to Z, inclusive (range)
[a-d[m-p]] a to d or m to p: [a-dm-p] (union)
[a-z&&[def]] d, e or f (intersection)
[ a-z&&[^bc]] a to z, except b and c: [ad-z] (minus)
[a-z&&[^m-p]] a to z, not m to p: [a -lq-z] (minus)

Predefined character classes

. Any character (which may or may not match line terminators)
\ d Numbers: [0-9]
\D Non-numbers: [^0-9]
\s White space characters: [ \t\n\x0B\f\r]
\S Non-white space characters :[^\s]
\w Word characters: [a-zA-Z_0-9]
\W Non-word characters: [^\w]

POSIX character class (only US- ASCII)
\p{Lower} Lowercase alphabetic characters: [a-z]
\p{Upper} Uppercase alphabetic characters: [A-Z]
\p{ASCII} All ASCII: [\x00-\x7F]
\p{Alpha} Alphabetic characters: [\p{Lower}\p{Upper}]
\p{Digit} Decimal digits: [0-9]
\p{Alnum} Alphanumeric characters :[\p{Alpha}\p{Digit}]
\p{Punct} Punctuation: !"#$%&'()* ,-./:;?@[\] ^_`{|}~
\p{Graph} Visible characters: [\p{Alnum}\p{Punct}]
\p{Print} Printable characters: [\p{Graph}\x20 ]
\p{Blank} Space or tab character: [ \t]
\p{Cntrl} Control character: [\x00-\x1F\x7F]
\p{XDigit} Hexadecimal System digits: [0-9a-fA-F]
\p{Space} Blank characters: [ \t\n\x0B\f\r]

java.lang.Character class (simple java character type)
\p{javaLowerCase} is equivalent to java.lang.Character.isLowerCase()
\p{javaUpperCase} is equivalent to java.lang.Character.isUpperCase()
\p{ javaWhitespace} Equivalent to java.lang.Character.isWhitespace()
\p{javaMirrored} Equivalent to java.lang.Character.isMirrored()

Classes for Unicode blocks and categories
\p{InGreek} Characters in Greek block (simple block)
\p{Lu} Uppercase letters (simple category)
\p{Sc} Currency symbols
\P{InGreek} All characters , except in Greek blocks (negation)
[\p{L}&&[^\p{Lu}]] All letters, except uppercase letters (minus)

Boundary matcher

^ Beginning of line
$ End of line
\b Word boundary
\B Non-word boundary
\A Beginning of input
\ G The end of the previous match
\Z The end of the input, only used for the last terminator (if any)
\z The end of the input

Greedy quantifier

X? Times
X{n,} X, at least n times
X{n,m} #X?? #X{n,}? X, at least n times
X{n,m}?

X? #X{n,} X, at least n times
X{n,m} X, at least n times, but not more than m times

Logical operator


XY X followed by Y
X|Y X or Y
(X) #\n Any matching nth capture group
Quotes

\ Nothing, but quotes the following characters

\Q Nothing, but quotes all characters up to \E \E Nothing, but ends with \Q Starting reference


Special construction (non-capturing)

(?:X) X, as a non-capturing group
(?idmsux-idmsux) Nothing, but will match the flag idms u The non-capturing group of the given flag i d m s u x on - off
(?=X) X) X, through a zero-width positive lookbehind
(?


Backslash, escape and quote

The backslash character ('\') is used for quote escape constructs, as shown in the table above defined, but also used to refer to other characters that will be interpreted as unescaped constructs. Therefore, the expression \\ matches a single backslash, and \{ matches an opening parenthesis. It is an error to use backslashes before any alphabetic characters that do not represent an escape construct; they are reserved for future extensions to the regular expression language. A backslash can be used before a non-alphabetic character, regardless of whether the character is part of an unescape construct. As required by the Java Language Specification, backslashes in strings in Java source code are interpreted as Unicode escapes or other character escapes. Therefore, you must use two backslashes in the string literal to indicate that the regular expression is protected from being interpreted by the Java bytecode compiler. For example, when interpreted as a regular expression, the string literal "\b" matches a single backspace character, while "\\b" matches a word boundary. The string literal "\(hello\)" is illegal and will cause a compile-time error; to match the string (hello), the string literal "\\(hello\\)" must be used.

Character Classes

Character classes can appear within other character classes and can contain the union operator (implicit) and the intersection operator (&&). The union operator represents a class that contains all characters in at least one of its operand classes. The intersection operator represents a class that contains all characters that are in both of its operand classes.

The precedence of character class operators is as follows, arranged from highest to lowest:

1 Literal value escaping \x

2 Grouping [...]

3 Range a-z 4 Union [a-e][i-u] 5 Intersection [a-z&&[aeiou]]

Note that different sets of metacharacters are actually is inside the character class, not outside the character class. For example, the regular expression . loses its special meaning within a character class, while the expression - becomes a range forming metacharacters.



Line terminator

Line terminator is a sequence of one or two characters that marks the end of a line for a sequence of input characters. The following codes are recognized as line terminators: New line (line feed) character ('\n'), Carriage return character ("\r\n") followed by a new line character, A single carriage return ('\r'),

Next line character ('\u0085'),

Line separator ('\u2028') or

Paragraph separator ('\ u2029).

If UNIX_LINES mode is activated, the newline character is the only recognized line terminator.

If the DOTALL flag is not specified, the regular expression . can match any character (except line terminators).

By default, the regular expressions ^ and $ ignore line terminators and only match the beginning and end of the entire input sequence, respectively. If MULTILINE mode is activated, ^ matching occurs at the beginning of the input and after the line terminator (at the end of the input). When in MULTILINE mode, $ matches only before a line terminator or at the end of the input sequence.

Groups and Captures

Capturing groups can be numbered by counting their opening brackets from left to right. For example, in the expression ((A)(B(C))), there are four such groups: 1 ((A)(B(C))) 2 \A 3 (B(C))

4 (C)

Group zero always represents the entire expression.


The capturing groups are named this way because in the match, every subsequence of the input sequence that matches these groups is saved. The captured subsequence can later be used in an expression via a Back reference, or can be obtained from the matcher after the matching operation has completed.

The capture input associated with a group is always the subsequence that most recently matched the group. If a group is calculated again due to quantization, its previously captured value (if any) will be retained when the second calculation fails. For example, comparing the string "aba" with the expression (a(b)?) match, sets the second group to "b". At the beginning of each match, all captured input is discarded.

A group starting with (?) is a pure non-capturing group, which does not capture text and does not count against the group total.

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

related articles:

What are the common scenarios in which closures can be exploited in JS? (Picture and text tutorial)

How to copy an object in js? (Picture and text tutorial)

Example of using js to implement a message board (code provided)

The above is the detailed content of Regular expressions (grammar). For more information, please follow other related articles on the PHP Chinese website!

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
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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment