Home >Web Front-end >JS Tutorial >Share some commonly used examples of regular expressions

Share some commonly used examples of regular expressions

零下一度
零下一度Original
2017-06-28 10:59:271111browse

Commonly used summary of regular expressions

Regular expressions are also called regular expressions and conventional expressions. (English: Regular Expression, often abbreviated as regex, regexp or RE in code), a concept in computer science. Regular expressions use a single string to describe and match a series of words that match a certain syntax rule. In many text editors, regular expressions are often used to retrieve and replace text that matches a certain pattern.

Regular expressions, is there anyone like me, who has learned it several times but is still confused. When I learn it, I always understand it, but after learning it, I forget it all. Well, in fact, I still haven’t practiced enough. The so-called review of the past and learning the new can become a teacher. Today, let me review this proud regular expression.

Why do we need regular expressions? In fact, it is because computers are stupid (this is not what I said). For example, 123456@qq.com, when we look at it, it is an email address, but the computer does not recognize it, so we have to use some languages ​​​​that computers understand to formulate rules and tell them. The one that conforms to this rule is a mailbox, so the computer can help us find the corresponding thing. So regular rules are used to set rules to complete some operations we need, such as login verification, searching for specified things, etc. It is redundant to say too much, let’s get to the point.

Define regular rules:


1 var re = new RegExp(“a”); //RegExp object. Parameters are the rules we want to make. There is a situation where this method must be used, which will be mentioned below.

2 var re = /a/; // It is recommended to use the abbreviation method for better performance. It cannot be empty or it will be regarded as a comment.

Regular Commonly used methods

1 test(): Find content that conforms to regular rules in a string. If found, it returns true, otherwise it returns false.

Usage: regular.test(string)

Example: Determine whether it is a number


##var str = '374829348791';

var re = /\ D/; // \D represents non-digit

if( re.test(str) ){ // Returns true, indicating that a non-digit is found in the string.

alert('Not all numbers');

}else{

alert('All numbers');

}

There are many symbols in regular expressions, which represent different meanings and are used to allow us to define different rules, such as \D above, and the following:

\s : Spaces

\S : Non-spaces

\d : Digits

\D : Non-digits

\w : Characters (letters, numbers, underscore_)

\W: Non-character examples: Are there any characters that are not numbers

(I will talk about some commonly used characters based on examples below, and finally do Summary. )

2 search(): Search for regular content in the string, and return the position where it appears (starting from 0, if more than one letter is matched, only the first one will be returned) letter position), if the search fails, -1 will be returned

Usage: String.search(regular)

Find the content of the compound regular expression in the string. Ignore case: i——ignore (regular is case-sensitive by default. If it is not case-sensitive, add i at the end of the regular)

Example: Find the letter b in the string, and not Case sensitive

var str = 'abcdef';

var re = /B/i;

// var re = new RegExp('B','i'); You can also write like this

alert( str.search(re) ); // 1

3 match() searches the content of the compound rule in the string. If the search is successful, it will return the content in the format of an array. If it fails, it will return null.

Usage: String.match (regular)

Quantifier: + At least one match occurs an undetermined number of times (matching means searching)

Global match: g ——global (default in regular rules, the search will end as long as the content of the compound rule is searched)

Example: Find all numbers in the specified format, find 123, 54, 33, 879 as follows

var str = 'haj123sdk54hask33dkhalsd879';

var re = /\d+/g; // Match at least one number each time and match globally if it is not a global match , when it finds the number 123, it stops. Only 123 will pop up. With global matching, it will search for those that match the rules from beginning to end. If there is no plus sign, the matching results are 1, 2, 3, 5, 4, 3, 3, 879, which is not what we want. With the plus sign, there will be at least one matching number each time.


##alert( str.match(re) ); // [123, 54, 33, 879]

4 replace(): Find a string that matches the regular pattern and replace it with the corresponding string. Return the replaced content.

Usage: String.replace(regular, new string/callback function) (in the callback function, the first parameter refers to the character that matches successfully each time)

| : means or.

例子:敏感词过滤,比如 我爱北京天安门,天安门上太阳升。------我爱*****,****上太阳升。即北京和天安门变成*号,

一开始我们可能会想到这样的方法:


var str = "我爱北京天安门,天安门上太阳升。";

var re = /北京|天安门/g; // 找到北京 或者天安门 全局匹配

var str2 = str.replace(re,'*');

alert(str2) //我爱**,*上太阳升

//这种只是把找到的变成了一个*,并不能几个字就对应几个*。

   

要想实现几个字对应几个*,我们可以用回调函数实现:


var str = "我爱北京天安门,天安门上太阳升。";

var re = /北京|天安门/g; // 找到北京 或者天安门 全局匹配

var str2 = str.replace(re,function(str){

alert(str); //用来测试:函数的第一个参数代表每次搜索到的符合正则的字符,所以第一次str指的是北京 第二次str是天安门 第三次str是天安门

var result = '';

for(var i=0;i

result += '*';

}

return result; //所以搜索到了几个字就返回几个*

});

alert(str2) //我爱*****,***上太阳升

//整个过程就是,找到北京,替换成了两个*,找到天安门替换成了3个*,找到天安门替换成3个*。

replace是一个很有用的方法,经常会用到。

正则中的字符

():,小括号,叫做分组符。就相当于数学里面的括号。如下:


var str = '2013-6-7';

var re1 = /\d-+/g; // 全局匹配数字,横杠,横杠数量至少为1,匹配结果为: 3- 6-

var re1 = /(\d-)+/g; // 全局匹配数字,横杠,数字和横杠整体数量至少为1 3-6-

var re2 = /(\d+)(-)/g; // 全局匹配至少一个数字,匹配一个横杠 匹配结果:2013- 6-

同时,正则中的每一个带小括号的项,都叫做这个正则的子项。子项在某些时候非常的有用,比如我们来看一个栗子。

例子:让2013-6-7 变成 2013.6.7


var str = '2013-6-7';

var re = /(\d+)(-)/g;

str = str.replace(re,function($0,$1,$2){

//replace()中如果有子项, //第一个参数:$0(匹配成功后的整体结果 2013- 6-),

// 第二个参数 : $1(匹配成功的第一个分组,这里指的是\d 2013, 6)

//第三个参数 : $1(匹配成功的第二个分组,这里指的是- - - )

return $1 + '.'; //分别返回2013. 6.

});

alert( str ); //2013.6.7

//整个过程就是利用子项把2013- 6- 分别替换成了2013. 6. 最终弹出2013.6.7

match方法也会返回自己的子项,如下:


var str = 'abc';

var re = /(a)(b)(c)/;

alert( str.match(re) ); //[abc,a,b,c]( 返回的是匹配结果 以及每个子项 当match不加g的时候才可以获取到子项的集合)

[] : 表示某个集合中的任意一个,比如 [abc] 整体代表一个字符 匹配 a b c 中的任意一个,也可以是范围,[0-9] 范围必须从小到大 。

[^a] 整体代表一个字符 :^写在[]里面的话,就代表排除的意思

例子:匹配HTML标签 比如

hahahah
找出标签

var re = /<[^>]+>/g; //Match the content of at least one non-right bracket between the left brackets (because there are attributes and other things in the tag), and then Match the right bracket var re = /<[\w\W]+>/g; //Match at least one character or non-character content in the middle of the left bracket, and then match the right bracket // In fact, find the left bracket, and then the middle There can be at least one content, until the right bracket is found, it represents a tag.

Escape characters

\s: Space

\S: Non-space

\d: Digit

\D: Not Number

\w: Character (letter, number, underscore_)

\W: Non-character

. : Any character

\. : True Point

\b: independent part (start, end, space)

\B: non-independent part

Let’s take a look at the last two:


##var str = 'onetwo';

var str2 ="one two";

var re = /one\b/; // e must be followed by an independent start, space, or end

alert( re.test(str) ); //false

alert ( re.test(str2) );//true

Example: Write a function that uses the class name to get the node:

Our previous You may have seen a function like this:


##function getByClass(parent,classname){

if(parent.getElementsByClassName){

return parent.getElementsByClassName(classname);

}

else{

var results = new Array();//Used to store all retrieved Elements whose class is box

var elems = parent.getElementsByTagName("*");

for(var i =0;i

if(elems[i].className==classname){

results.push(elems[i]);

}

}

return results;

}

}

In fact, there is a problem. For example, if a tag contains If there are two classes, or there are classes with the same name, such as

,
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