Home > Web Front-end > JS Tutorial > How to use regular expressions in Javascript

How to use regular expressions in Javascript

小云云
Release: 2018-01-05 17:57:44
Original
1742 people have browsed it

Regular expressions may be a bunch of incomprehensible characters in people’s minds, but it is these symbols that enable efficient operations on strings. Regular expression (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 on information in strings. Common situations Yes, the problem itself is not complicated, but without regular expressions it becomes a big problem. Regular expressions in JavaScript are very important knowledge. This article will introduce the basic syntax of regular expressions.

Definition

Regular expression (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 process strings. The information in realizes search, replacement and extraction operations

Regular expressions in JavaScript 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. There are many places where regular expressions can be used in JavaScript. 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 function is to find out the conditions that satisfy the condition from a bunch of strings substring. For example, if I define a regular expression in JavaScript:


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

, 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
Copy after login

String.prototype.replace method

Used to replace substrings in a string


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

String.prototype.split method

Used to split the string


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

String.prototype.match method

Used to capture subcharacters in the string 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"]
Copy after login

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

RegExp.prototype.test method

is used to test whether the string contains a substring


/hello/.test("abchello"); // true
Copy after login

RegExp.prototype.exec Method

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

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"]
Copy after login

2. Regular expression The formula 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, lastIndex will be pushed back until no matching character is found and null will be returned. , and then capture again from scratch. 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
Copy after login

Basics of regular expressions

Metacharacters

The first section above uses /hello/ as an example, but in actual applications it may You will 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.

Metacharacter:


//匹配数字: \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"]
Copy after login

Antonym metacharacter, written by changing the lowercase letters above to uppercase, for example, matches all characters that are not numbers : \D

There are also some metacharacters used to represent repetitions, which will be introduced below.

Character range

Use the symbol - in [] to represent a character range. Such as:


// 匹配字母 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
Copy after login

Repetition & Greedy and Lazy

First of all, let’s talk about repetition. When we want to match some repeated characters, we need to use some and Repeat the relevant regular expression, written as follows


//重复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"]
Copy after login

As you can see from the above results, when the number following the character test can be repeated 0 or more times, the regular expression The substring captured by the formula will return as many numbers as possible. For example, if /test\d*/ matches test123, test123 will be returned, not test or test12.

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

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


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

字符转义

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

/\./.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"]
Copy after login

但是当正则表达式没有全局属性,且正则表达式中有分组的时候,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"]
Copy after login

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


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

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


"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"]
Copy after login

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

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


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

后向引用

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

比如


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

断言

 (?: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"
Copy after login

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


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

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


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

处理选项

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"]
Copy after login

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


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

相关推荐:

Replace中的正则表达式_正则表达式

JS使用正则表达式找出最长连续子串长度

关于HTML用正则表达式检验表格方法

The above is the detailed content of How to use regular expressions in Javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template