Home Web Front-end JS Tutorial Detailed explanation of group matching and backreference of JavaScript regular expressions_javascript skills

Detailed explanation of group matching and backreference of JavaScript regular expressions_javascript skills

May 16, 2016 pm 03:11 PM

语法

元字符:(pattern)  作用:用于反复匹配的分组

属性$1~$9  如果它(们)存在,用于得到对应分组中匹配到的子串

\1或$1  用于匹配第一个分组中的内容

\2或$2  用于匹配第一个分组中的内容

...

\9或$9  用于匹配第一个分组中的内容

用法示例

var reg = /(A+)((B|C|D)+)(E+)/gi;//该正则表达式有4个分组
//对应关系
//RegExp.$1 <-> (A+)
//RegExp.$2 <-> ((B|C|D)+)
//RegExp.$3 <-> (B|C|D)
//RegExp.$4 <-> (E+) 
Copy after login

以上的代码也同时给出了$1~$9的用法

$1~$9是正则表达式预定义的静态属性,通过RegExp.$1引用

分组嵌套关系说明

上述代码也可以说明分组的嵌套关系

//测试环境 Chrome浏览器
var str = "ABCDE";
var reg = /(A+)((B|C|D)+)(E+)/gi;
str.match(reg);//输出:["ABCDE"]
reg.exec(str,'i');//输出:["ABCDE", "A", "BCD", "D", "E"]
RegExp.$1;//输出:"A"
RegExp.$2;//输出:"BCD"
RegExp.$3;//输出:"D"
RegExp.$4;//输出:"E" 
Copy after login

这样就可以很明白的看出分组的嵌套关系了

总结来说:大的分组中存在小的分组时,小的分组是排在该大分组后面的分组,以此类推

第二部分

这部分主要讲解类似于"\1"这个东西的用法

分组匹配之反向引用

语法

元字符 \1~\9  作用:用来表示前面以匹配的字符或分组的一个引用

用法示例

参考文章:[原]AS3 js正则表达式 反向引用(backreference)

上面说的可能有些拗口,下面给一个例子:

//一般情况,当我们想匹配任意两个相同的字符(复杂一点就是两个相同的分组)时,往往可以借助下面的写法
//说明:
//(\w)用来匹配任何除了换行和制表符的字符, 而1是对(\w)的一个引用, 所以你可以理解成: (\w)\1 就是(\w)(\w)
//但是,
//(\w)\1 和 (\w)(\w)的不同之处在于, (\w)(\w)表示任意两个连续的字符, 比如Ac, MM, K9, 都可以,
// 但(\w)\1只能是AA, CC, 99 这样连续相同的字符
//所以, 你可以这样理解, \1 是对(\w)的一个实例化引用, 当(\w) 匹配到A时, \1 被表达成A, 当(\w)匹配9时, \1 被表示成9
//说了这么多, 可能有些废话, 下面这个例子就很好理解了
var str = "AA Am 99";
var reg = /(\w)\1/g;
str.match(reg);//输出: ["AA", "99"] 
Copy after login

所以, 参照上边我所引用的文章中给出的 "关键字搜索高亮显示的正则表达用法" 的例子, 我给出自己改进的小的DEMO

虽然这个DEMO没有用到任何的关于反向引用的知识点::>_<::

//测试环境 Chrome浏览器
var key = "keywords";//搜索的关键字
var text = " I am a text, and I have a keywords before this";//待匹配的文本
var reg = new RegExp("("+key+")","g");
text.replace(reg,"<span style='color:red'>$1</span>");//输出: " I am a text, and I have a <span style='color:red'>keywords</span> before this"
Copy after login

下面给大家详细介绍下正则表达式之反向引用

示例1:

public static void main(String[] args) { 
 String s="99-3933"; 
 boolean b=Pattern.matches("([\\d])\\1[-]([3])\\1\\2{2}", s); 
 System.out.println(b); 
}
Copy after login

反向引用,匹配重复的数字

([\d])====>\1

([3])====>\2

示例2:

public class test { 
 public static void main(String[] args) { 
  String s="99-393399-3933"; 
  boolean b=Pattern.matches("(([\\d])\\2[-]([3])\\2\\3{2})\\1", s); 
  System.out.println(b); 
 } 
}
Copy after login
Statement of this Website
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

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins 10 jQuery Fun and Games Plugins Mar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header Background jQuery Parallax Tutorial - Animated Header Background Mar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

Getting Started With Matter.js: Introduction Getting Started With Matter.js: Introduction Mar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

Auto Refresh Div Content Using jQuery and AJAX Auto Refresh Div Content Using jQuery and AJAX Mar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

See all articles