Home  >  Article  >  Web Front-end  >  The use and basic syntax of regular expressions in Javascript_regular expressions

The use and basic syntax of regular expressions in Javascript_regular expressions

韦小宝
韦小宝Original
2017-12-15 12:12:201376browse

Regular Expression (Regular Expression) is a grammatical specification of a simple language. It is a powerful, convenient and efficient text processing tool. In the actual development process, Regular Expression starts Playing a very important role, regular expressions are also more difficult to learn and difficult to understand. Come and take a look with the editor today! !

Previous words

Regular expressions may be a bunch of incomprehensible characters in people’s minds, but it is these symbols that realize Efficient manipulation of strings. As is often the case, the problem itself is not complicated, but the lack of regular expressions becomes a big problem. Regular expressions in JavaScript are very important knowledge. This article will introduce the basic syntax of regular expressions

Definition

Regular expressions ( Regular Expression) is a grammatical specification of a simple language. It is a powerful, convenient and efficient text processing tool. It is used in some methods to implement search, replacement and extraction operations for information in strings

 javascript The regular expressions in are represented by RegExp objects. There are two ways of writing: one is literal writing; the other is constructor writing.

Regular expressions are particularly useful for processing strings. In JavaScript There are many places where regular expressions can be used. This article summarizes the basic knowledge of regular expressions and the use of regular expressions in Javascript.

The first part briefly lists the usage scenarios of regular expressions in JavaScript; the second part introduces the basic knowledge of regular expressions in detail and writes some examples for easy understanding.

The content of this article is my own summary after reading the regular expression writing method and the js regular expression chapter in the Rhino book, so the content may have omissions and imprecision. If there are any experts who pass by and find errors in the article, please correct them!

The use of regular expressions in Javascript

A regular expression can be thought of as a characteristic description of a character fragment, and its Its function is to find substrings that meet the conditions from a bunch of strings. For example, if I define a regular expression in JavaScript:

var reg=/hello/  或者 var reg=new RegExp("hello")

, then this regular expression can be used to find the word hello from a bunch of strings. The result of the "find" action may be to find the position of the first hello, replace hello with another string, find all hellos, etc. Below is a list of functions that can use regular expressions in JavaScript, and a brief introduction to the functions of these functions. More complex usage will be introduced in the second part.

String.prototype.search method

is used to find the index of the first occurrence of a substring in the original string. If not, it returns -1

"abchello".search(/hello/); // 3


String.prototype.replace method

is used to replace substrings in the string String

"abchello".replace(/hello/,"hi");  // "abchi"

String.prototype.split method

is used to split the string

"abchelloasdasdhelloasd".split(/hello/); //["abc", "asdasd", "asd"]

String.prototype.match method

is used to capture substrings in a string into an array. By default, only one result is captured into the array. When the regular expression has the "global capture" attribute (add parameter g when defining the regular expression), all results will be captured into the array.

"abchelloasdasdhelloasd".match(/hello/); //["hello"]
"abchelloasdasdhelloasd".match(/hello/g); //["hello","hello"]

The performance of the match method is different whether the regular expression used as a match parameter has global attributes or not. This will be discussed later in the regular expression grouping.

RegExp.prototype.test method

is used to test whether the string contains substrings

/hello/.test("abchello"); // true

RegExp.prototype.exec method

is similar to the string match method. This method also captures strings that meet the conditions from the string into an array, but there are two a difference.

1. The exec method can only capture one substring into an array at a time, regardless of whether the regular expression has global attributes

var reg=/hello/g;
reg.exec("abchelloasdasdhelloasd");  // ["hello"]

2 . The regular expression object (that is, the RegExp object in JavaScript) has a lastIndex attribute, which is used to indicate where to start capturing next time. After each execution of the exec method, the lastIndex will be pushed back until no matching is found. Characters are returned as null and then captured again from the beginning. This property can be used to iterate over substrings in a captured string.

var reg=/hello/g;
reg.lastIndex; //0
reg.exec("abchelloasdasdhelloasd"); // ["hello"]
reg.lastIndex; //8
reg.exec("abchelloasdasdhelloasd"); // ["hello"]
reg.lastIndex; //19
reg.exec("abchelloasdasdhelloasd"); // null
reg.lastIndex; //0

Regular expression basics

Metacharacters

The first section above takes /hello/ as an example, but in actual applications you may encounter such requirements: match a string of uncertain numbers, match the starting position, match the ending position, and match blank characters. This is where metacharacters can be used.

Metacharacters:

//匹配数字: \d
"ad3ad2ad".match(/\d/g); // ["3", "2"]
//匹配除换行符以外的任意字符: .
"a\nb\rc".match(/./g); // ["a", "b", "c"]
//匹配字母或数字或下划线 : \w
"a5_ 汉字@!-=".match(/\w/g); // ["a", "5", "_"]
//匹配空白符:\s
"\n \r".match(/\s/g); //[" ", " ", ""] 第一个结果是\n,最后一个结果是\r
//匹配【单词开始或结束】的位置 : \b
"how are you".match(/\b\w/g); //["h", "a", "y"] 
// 匹配【字符串开始和结束】的位置: 开始 ^ 结束 $
"how are you".match(/^\w/g); // ["h"]

Antonym metacharacters, written by changing the lowercase letters above to uppercase, for example, match all that are not Number characters: \D

另外还有一些用来表示重复的元字符,会在下面的内容中介绍。

字符范围

在 [] 中使用符号 -  ,可以用来表示字符范围。如:

// 匹配字母 a-z 之间所有字母
/[a-z]/
// 匹配Unicode中 数字 0 到 字母 z 之间的所有字符
/[0-z]/ 
// unicode编码查询地址:
//https://en.wikibooks.org/wiki/Unicode/Character_reference/0000-0FFF
//根据上面的内容,我们可以找出汉字的Unicode编码范围是 \u4E00 到 \u9FA5,所以我们可以写一个正则表达式来判断一个字符串中是否有汉字
/[\u4E00-\u9FA5]/.test("测试"); // true

重复 & 贪婪与懒惰

首先来讲重复,当我们希望匹配一些重复的字符时,就需要用到一些和重复相关的正则表达式,写法如下

//重复n次 {n}
"test12".match(/test\d{3}/); // null
"test123".match(/test\d{3}/); // ["test123"]
//重复n次或更多次 {n,}
"test123".match(/test\d{3,}/); // ["test123"]
//重复n到m次
"test12".match(/test\d{3,5}/); // null
"test12345".match(/test\d{3,5}/); // ["test12345"]
"test12345678".match(/test\d{3,5}/); // ["test12345"]
// 匹配字符test后边跟着数字,数字重复0次或多次
"test".match(/test\d*/); // ["test"]
"test123".match(/test\d*/); // ["test123"]
//重复一次或多次
"test".match(/test\d+/) ; // null
"test1".match(/test\d*/); //["test1"]
//重复一次或0次
"test".match(/test\d?/) ; // null
"test1".match(/test\d?/); //["test1"]

从上面的结果可以看到,字符test后边跟着的数字可以重复0次或多次时,正则表达式捕获的子字符串会返回尽量多的数字,比如/test\d*/匹配 test123 ,返回的是test123,而不是test或者test12。

正则表达式捕获字符串时,在满足条件的情况下捕获尽可能多的字符串,这就是所谓的“贪婪模式”。

对应的”懒惰模式“,就是在满足条件的情况下捕获尽可能少的字符串,使用懒惰模式的方法,就是在字符重复标识后面加上一个 "?",写法如下

// 数字重复3~5次,满足条件的情况下返回尽可能少的数字
"test12345".match(/test\d{3,5}?/); //["test123"]
// 数字重复1次或更多,满足条件的情况下只返回一个数字
"test12345".match(/test\d+?/); // ["test1"]

字符转义

在正则表达式中元字符是有特殊的含义的,当我们要匹配元字符本身时,就需要用到字符转义,比如:

/\./.test("."); // true

分组 & 分支条件

正则表达式可以用 " ()  " 来进行分组,具有分组的正则表达式除了正则表达式整体会匹配子字符串外,分组中的正则表达式片段也会匹配字符串。

分组按照嵌套关系和前后关系,每个分组会分配得到一个数字组号,在一些场景中可以用组号来使用分组。

在 replace、match、exec函数中,分组都能体现不同的功能。

replace函数中,第二个参数里边可以用 $+数字组号来指代第几个分组的内容,如:

" the best language in the world is java ".replace(/(java)/,"$1script"); // " the best language in the world is javascript "
"/static/app1/js/index.js".replace(/(\/\w+)\.js/,"$1-v0.0.1.js"); //"/static/app1/js/index-v0.0.1.js"    (\/\w+)分组匹配的就是 /index ,

在第二个参数中为其添加上版本号

match函数中,当正则表达式有全局属性时,会捕获所有满足正则表达式的子字符串

"abchellodefhellog".match(/h(ell)o/g); //["hello", "hello"]

但是当正则表达式没有全局属性,且正则表达式中有分组的时候,match函数只会返回整个正则表达式匹配的第一个结果,同时会将分组匹配到的字符串也放入结果数组中:

"abchellodefhellog".match(/h(ell)o/); //["hello", "ell"]
// 我们可以用match函数来分解url,获取协议、host、path、查询字符串等信息
"http://www.baidu.com/test?t=5".match(/^((\w+):\/\/([\w\.]+))\/([^?]+)\?(\S+)$/);
// ["http://www.baidu.com/test?t=5", "http://www.baidu.com", "http", "www.baidu.com", "test", "t=5"]

exec函数在正则表达式中有分组的情况下,表现和match函数很像,只是无论正则表达式是否有全局属性,exec函数都只返回一个结果,并捕获分组的结果

/h(ell)o/g.exec("abchellodefhellog"); //["hello", "ell"]

当正则表达式需要匹配几种类型的结果时,可以用到分支条件,例如

"asdasd hi asdad hello asdasd".replace(/hi|hello/,"nihao"); //"asdasd nihao asdad hello asdasd"
"asdasd hi asdad hello asdasd".split(/hi|hello/); //["asdasd ", " asdad ", " asdasd"]

 注意,分支条件影响它两边的所有内容, 比如 hi|hello  匹配的是hi或者hello,而不是 hiello 或者 hhello

分组中的分支条件不会影响分组外的内容

"abc acd bbc bcd ".match(/(a|b)bc/g); //["abc", "bbc"]

后向引用

正则表达式的分组可以在其后边的语句中通过  \+数字组号来引用

比如

// 匹配重复的单词
/(\b[a-zA-Z]+\b)\s+\1/.exec(" asd sf hello hello asd"); //["hello hello", "hello"]

断言

 (?:exp) , 用此方式定义的分组,正则表达式会匹配分组中的内容,但是不再给此分组分配组号,此分组在replace、match等函数中的作用也会消失,效果如下:

/(hello)\sworld/.exec("asdadasd hello world asdasd") // ["hello world", "hello"],正常捕获结果字符串和分组字符串
/(?:hello)\sworld/.exec("asdadasd hello world asdasd") // ["hello world"]
"/static/app1/js/index.js".replace(/(\/\w+)\.js/,"$1-v0.0.1.js"); //"/static/app1/js/index-v0.0.1.js"
"/static/app1/js/index.js".replace(/(?:\/\w+)\.js/,"$1-v0.0.1.js"); //"/static/app1/js$1-v0.0.1.js"

(?=exp) 这个分组用在正则表达式的后面,用来捕获exp前面的字符,分组中的内容不会被捕获,也不分配组号

/hello\s(?=world)/.exec("asdadasd hello world asdasd") // ["hello "]

(?!exp)  和前面的断言相反,用在正则表达式的后面,捕获后面不是exp的字符,同样不捕获分组的内容,也不分配组号

/hello\s(?!world)/.exec("asdadasd hello world asdasd") //null

处理选项

javascript中正则表达式支持的正则表达式有三个,g、i、m,分别代表全局匹配、忽略大小写、多行模式。三种属性可以自由组合共存。

// 全局匹配 g 
"abchelloasdasdhelloasd".match(/hello/); //["hello"]
"abchelloasdasdhelloasd".match(/hello/g); //["hello","hello"]
//忽略大小写 i
"abchelloasdasdHelloasd".match(/hello/g); //["hello"]
"abchelloasdasdHelloasd".match(/hello/gi); //["hello","Hello"]

在默认的模式下,元字符 ^ 和 $ 分别匹配字符串的开头和结尾处,模式 m 改变了这俩元字符的定义,让他们匹配一行的开头和结尾

"aadasd\nbasdc".match(/^[a-z]+$/g); //null 字符串^和$之间有换行符,匹配不上 [a-z]+ ,故返回null
"aadasd\nbasdc".match(/^[a-z]+$/gm); // ["aadasd", "basdc"] ,改变^$的含义,让其匹配一行的开头和末尾,可以得到两行的结果

总结

以上所述是小编给大家介绍的Javascript中正则表达式的使用及基本语法,希望对大家有所帮助!!

相关推荐:

In-depth analysis of sub-patterns of regular expressions

Usage of the shortest matching pattern in regular expressions

How to use regular expressions to mask keywords

The above is the detailed content of The use and basic syntax of regular expressions in Javascript_regular expressions. 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