What is a regular expression?
Regular expressions are search patterns formed by a sequence of characters. When you search for data in text, you can use search patterns to describe what you are looking for. The regular expression can be a simple character or a more complex pattern. Regular expressions can be used for all text search and text replacement operations.
Regular expression creation
- Literal (direct)
// 在一对反斜线中写正则表达式内容,如/abc/
// 正则表达式里面不需要加引号 不管是数字型还是字符串型
var pattern=/正则表达式/修饰符;
var pattern=/qwer/igm;
- Constructor
//构造正则表达式的实例,如new RexExp('abc')
//内部传入的参数为字符串/字符串的变量
var reg =new RegExp("正则表达式","修饰符")
var reg =new RegExp("hello","g");
Character classification
Normal characters
Letters, numbers, underscores, Chinese characters, symbols with no special meaning (,;!@, etc.)
In fact, characters that are not special characters are ordinary characters
Special characters
\: Escape special characters into ordinary characters
Mode modifier
i: ignoreCase, ignore case when matching
m: multiline, multi-line matching
g: global, global match
When creating a regular literal, the pattern modifier is written after a pair of backslashes
Regular expression example methods
- exec---->> can be used to match the string that meets the regular expression in the string
If it matches, the return value is a result array: [matched content, index: the starting position of the match in str, input: parameter string, groups: undefined], r returns null if it fails to match
E.g:
var str = 'hello world hello';
var reg1 = /hello/;
var reg2 = /hello/g; //g表示全局匹配,也就是会匹配到str中所有满足正则表达式条件的字段
var reg3 = /exe/g;
console.log(reg1.exec(str)); //[ 'hello', index: 0, input: 'hello world hello', groups: undefined ]
console.log(reg2.exec(str)); //[ 'hello', index: 0, input: 'hello world hello', groups: undefined ]
console.log(reg3.exec(str)); // null //str中并不存在exe字段,所以输出null
// 如果是全局模式的正则验证 还可以使用循环进行输出
var reg = /hello/g;
var str = 'hello world hello hello good';
while(true)
var result = reg.exec(str);
if(!result){
break;
}
console.log(result[0],result["index"],reg.lastIndex); //hello 18 23
}
The place to pay attention to is
1) If there is a modifier "g" in the regular expression, at this time, the lastIndex property will be maintained in the instance reg of the regular expression to record the next starting position. When the exec is executed for the second time, the search starts from lastIndex .
2) If there is no modifier "g" in the regular expression, the lastIndex property will not be maintained, and retrieval will be performed from the start position each time
2.test ---->> is used to test whether there is a string that can match the regular expression in the string to be tested, if there is a string that can match the regular expression, it returns true, otherwise it returns false
E.g:
var str = 'hello world';
var reg1 = /world/;
var reg2 = /Regex/;
console.log(reg1.test(str)); //返回true
console.log(reg2.test(str)); //返回false
In fact, I prefer to put the string str in test() to look better (intuitive proofreading)~~~
var reg1 = /world/;
var reg2 = /Regex/;
console.log(reg1.test(hello world)); //返回true
console.log(reg2.test(hello world)); //返回false
//由结果可知
//字符串中是否有可以匹配到正则表达式的字符串world,所以返回true
3.toString/toLocaleString --->> Convert the content of the regular expression into a literal string/string with local characteristics (no effect in JS)
E.g:
var reg1 = /hello/;
console.log(reg1.toString()); // /hello/ string
console.log(reg1.toLocaleString()); // /hello/ string
4.valueOf ------>> returns the basic numeric value of a Number object
Its role is to return the regular expression itself
E.g:
var reg1 = /hello/;
console.log(reg1.valueOf()); // /hello/ 返回正则表达式本身
Regular expression instance properties
- lastIndex
In the rookie tutorial, the astIndex attribute is used to specify the starting position of the next match. This attribute can only be used when the flag g is set.
Therefore, when global matching is not set, the attribute value is always 0
When global matching is set, every time exec/test is executed to match, latIndex will move to the next position of the matched string. When there is no string that can be matched again after the pointed position, the next execution of exec returns null , the test execution returns false , and then lastIndex reset to zero , and a round of matching is performed from the beginning of the string
It can be understood that the starting point search is the lastIndex
In short, the global matching character g plays a role in maintaining lastindex. Without g, lastindex has no effect.
E.g:
var reg =new RegExp('hello')
var reg1 = /hello/g;
var str = 'hello hello hello'; //字符串最后一个数的后面存在一个空字符'hello hello hello""'
console.log('正则表达式构造函数');
console.log(reg.lastIndex); //0
console.log(reg.exec(str)); //返回第一个hello
console.log(reg.lastIndex); //0
console.log('正则表达式字面量');
console.log(reg1.lastIndex); //0
console.log(reg1.exec(str)); //[ 'hello', index: 0, input: 'hello hello hello', groups: undefined ] 第一个hello
//每执行一次exec/test来匹配,latIndex就会移向匹配到的字符串的下一个位置 所以当前lastIndex正好指向空格
console.log(reg1.lastIndex); //5
console.log(reg1.lastIndex); //5
console.log(reg1.exec(str)); //返回第二个hello [ 'hello', index: 6, input: 'hello hello hello', groups: undefined ]
//每执行一次exec/test来匹配,latIndex就会移向匹配到的字符串的下一个位置 所以当前lastIndex正好指向空格
console.log(reg1.lastIndex); //11
console.log(reg1.lastIndex); //11
console.log(reg1.exec(str)); //返回第三个hello [ 'hello', index: 12, input: 'hello hello hello', groups: undefined ]
//每执行一次exec/test来匹配,latIndex就会移向匹配到的字符串的下一个位置 所以当前lastIndex正好指向空格
console.log(reg1.lastIndex); //17 //因为字符串最后一个数的后面存在一个空字符'hello hello hello""'
console.log(reg1.exec(str)); //null
// 当指向的位置后没有可以再次匹配的字符串时,重新开始找
console.log(reg1.lastIndex); //0
console.log(reg1.exec(str)); //返回第一个hello [ 'hello', index: 0, input: 'hello hello hello', groups: undefined ]
2.ignoreCase, global, multiline------>> Determine whether there are three pattern modifiers in the regular expression: ignore case, global matching, and multiline matching
E.g:
var reg1 = /hello/igm;
console.log(reg1.ignoreCase); //true 忽略大小写
console.log(reg1.global); //true 全局匹配
console.log(reg1.multiline); //true 多行匹配
3.source --->> returns a regular expression in literal form (similar to toString)
E.g:
var reg1 = /hello/igm;
console.log(reg1.source); //hello 返回正则表达式本身
Regular expression syntax-metacharacters
All letters and numbers in regular expressions are matched literally. Javascript regular expression syntax also supports non-letter character matching. These characters need to be escaped with a backslash \ as a prefix.
Literal character
- Character set
A character set, also called a character group. Match any character in the set. You can use the hyphen'-' to specify a range
Square brackets are used to find characters in a certain range :
[abc] Find any character between square brackets
var str = 'abc qwe abd'
var reg1 = /[abc]/;// 只要包含有a 或者 包含有b 或者包含有c 都返回为true
console.log(reg1.test(str)); //true
[0-9] Find any number from 0 to 9
var str = 'abc qwe abd1'
var reg1 = /[0-9]/igm;
console.log(reg1.test(str)); //true
An antisense or supplementary character set, also called an antisense character set. In other words, it matches any character that is not in the brackets. You can also specify a range of characters by using a hyphen'-'.
Note : ^ written in [] is the supplementary character set
//反义字符组
//它匹配任意不在括号内的字符。你也可以通过使用连字符 '-' 指定一个范围内的字符。
var str = 'abc qwe abd1,2'
console.log(str);
var reg1 = /[^abc]/igm; //除了abc,可取其他任意字符
console.log(reg1.exec(str));
//[ 'q', index: 4, input: 'abc qwe abd1,2', groups: undefined ]
console.log(reg1.test(str)); //true //
- Boundary character
^ The match input begins. Indicates to match the text at the beginning of the line (who starts with). If the multiline flag is set to true, the character will also match the beginning of a line break.
E.g:
// 以 ^ 开始
// 必须是以hel开头的字符串才会满足
var reg = /^[hel]/;
console.log(reg.exec(hello world hello Regexp)); // [ 'h', index: 0, input: 'hello world hello Regexp', groups: undefined ]
console.log(reg.test(hello world hello Regexp)); //true
console.log(reg.test('aabcd')); // false
- $ Matches the end of the input. Indicates the text at the end of the match line (ends with whom). If the multiline flag is set to true, the character will also match the end before a line break.
E.g:
// 以 $ 结束
// 必须是以exp结尾的字符串才会满足
var reg1 = /[exp]$/;
console.log(reg1.exec(hello world hello Regexp));
// [
// 'p',
// index: 23,
// input: 'hello world hello Regexp',
// groups: undefined
// ]
console.log(reg1.test(hello world hello Regexp)); //true
console.log(reg.test('aabcd')); // false
- If ^ and $ are together, it must be an exact match.
// 如果 ^和 $ 在一起,表示必须是精确匹配
var reg2 = /^hello$/;
console.log(reg2.test('hello')); //true
console.log(reg2.test('helloeeee')); //false
4. Character set used with "^" and "$"
// 字符集合与"^"和"$"一起使用
// 三选一 只有是a 或者是 b 或者是c 这三个字母才返回 true
var rg1 = /^[abc]$/; //单个匹配
console.log(rg1.test('aa'));//false
console.log(rg1.test('a'));//true
console.log(rg1.test('b'));//true
console.log(rg1.test('c'));//true
console.log(rg1.test('abc'));//false
//26个英文字母任何一个字母返回 true - 表示的是a 到z 的范围
var reg = /^[a-z]$/
console.log(reg.test('a'));//true
console.log(reg.test('z'));//true
console.log(reg.test('A'));//false
//字符组合
// 26个英文字母(大写和小写都可以)任何一个字母返回 true
var reg1 = /^[a-zA-Z0-9]$/;
//取反 方括号内部加上 ^ 表示取反,只要包含方括号内的字符,都返回 false 。
var reg2 = /^[^a-zA-Z0-9]$/;
console.log(reg2.test('a'));//false
console.log(reg2.test('B'));//false
console.log(reg2.test(8));//false
console.log(reg2.test('!'));//true
console.log(reg2.test('?'),'其他字符'); //true
console.log(reg2.test(':'),'其他字符'); //true
console.log(reg2.test('='),'其他字符'); //true
\b matches a zero-width word boundary, which represents a word (not character) boundary, that is, the position between a word and a space, or between a character (\w) and the beginning or end of a string s position.
\B matches a zero-width non-word boundary, the opposite of "\b".
I think this is very easy to understand. I don’t know how to state it.
E.g:
//
var str = 'this is a former browser';
// \b 匹配一个零宽单词边界,表示一个单词(而非字符)边界,
// 也就是单词和空格之间的位置,或者字符(\w)与字符串开头或者结尾之间的位置。
var text = "this is a former browser!";
console.log(text.match(/\b.s\/g)); //is //这个is是单个的is
// \B 匹配一个零宽非单词边界,与"\b"相反
var text = "this is a former browser!";
console.log(text.match(/\B.s/g)); // is ws //这个is是this里面的is
- Character class
Putting literal characters alone in square brackets forms a character class, and a character class can match any character it contains. For example: /[abc]/ matches any of the letters "a", "b", and "c". The "^" symbol is used to define negative character classes, for example:matches all characters except "a", "b", and "c". Character classes can use hyphens to indicate character ranges, for example: /[az]/, to match any letters and numbers in the Latin alphabet, [a-zA-Z0-9]
The memory method recommended by the teacher---->>Associative memory method
Combined with English original memory:
d ==> digit
s ==> space (blank)
w ==> word
Next, we analyze one by one. In short, the lowercase and uppercase character classes are mutually antonyms.
- "." Any single character except line feed \n and carriage return
//"." 除换行符\n之外的任何单个字符
var str = '\ngood World Hello\r JavaScript';
var reg1 = /./g;
console.log(reg1.exec(str));
// [
// 'g',
// index: 1,
// input: '\ngood World Hello\r JavaScript',
// groups: undefinedl;
// ]
console.log(reg1.test('\ngood World Hello JavaScript')); //true 字符串中有满足条件的就返回true
console.log(reg1.test('\n')); //false
console.log(reg1.test('\r')); //false
- \d matches a digit character, equivalent to [0-9]
// \d 匹配一个数字字符,等效于[0-9]
// 以数字开头
var str = '123Hello World Hello JavaScript';
var str1 = 'Hello World Hello 123JavaScript';
var reg4 = /^\d/;
console.log(reg4.exec(str));
console.log(reg4.test(str),'数字开头时'); //true
console.log(reg4.test(str1)); //false
// \D 等效于[^0-9]
// 不以数字开头
var str = 'Hello World Hello 123JavaScript';
var str1 = '123Hello World Hello 123JavaScript';
console.log(str);
var reg1 = /^\D/;
console.log(reg1.exec(str));
console.log(reg1.test(str),'不以数字开头'); //true 不以数字开头
console.log(reg1.test(str1),'以数字开头'); //false 不以数字开头
- \s matches any Unicode blank character, including spaces, tabs, form feeds, etc., equivalent to [\f\t\n\r]
// \s 匹配任何Unicode空白字符,包括空格、制表符、换页符等,等效于[\f\t\n\r]
// 以空白字符开头
var str = ' Hello World Hello 123JavaScript';
var reg1 = /^\s/;
console.log(reg1.exec(str),'以空白字符开头');
// [
// ' ',
// index: 0,
// input: ' Hello World Hello 123JavaScript',
// groups: undefined
// ]
console.log(reg1.test(str),'以空白字符开头'); //true
// \S 等效于**[^\f\t\n\r]
// 不以空白字符开头
var str = 'Hello World Hello 123JavaScript';
var reg1 = /^\S/;
console.log(reg1.exec(str));
// [
// 'H',
// index: 0,
// input: 'Hello World Hello 123JavaScript',
// groups: undefined
// ]
console.log(reg1.test(str)); //true
- \w matches any single character including underscore, including A~Z, a~z, 0~9 and underscore "", which is equivalent to [a-zA-Z0-9_]
// \w 匹配包括下划线的任何单个字符,包括A~Z,a~z,0~9和下划线"",等效于[a-zA-Z0-9_]/
var str = 'Hello World Hello JavaScript';
// \w -> [a-zA-Z0-9_]
var reg1 = /^\w/;
console.log(reg1.exec(str),'www');
// [
// 'H',
// index: 0,
// input: 'Hello World Hello JavaScript',
// groups: undefined
// ]
console.log(reg1.test(str)); //true
console.log(reg1.test('!Hello World Hello JavaScript')); //false
- \W matches any single character that does not include the underscore, including A~Z, a~z, 0~9 and the underscore "", which is the opposite of \w
// \W -> [^a-zA-Z0-9_]
var str = '!Hello World Hello JavaScript';
var reg2 = /^\W/;
console.log(reg2.exec(str));
// [
// '!',
// index: 0,
// input: '!Hello World Hello JavaScript',
// groups: undefined
// ]
console.log(reg2.test(str)); //true
Quantifier
character | meaning |
---|---|
* | >=0 times |
+ | ≥1 times |
? | 0 or 1 time |
{n} | n times |
{n,} | ≥n times |
{n,m} | n to m times |
- X* matches the previous pattern x ---> 0 or more times. Equivalent to {0,}
// * 允许出现0次或多次
var reg = new RegExp(/^a*$/);
console.log(reg.test("a")); // true
console.log(reg.test("aaaaaaaaaaaaa")); // true
console.log(reg.test("")); // true
- X+ matches the previous pattern x ---> 1 or more times. Equivalent to {1,}.
// + 允许出现1次或多次
var reg2 = new RegExp(/^a+$/);
console.log(reg2.test("a")); // true
console.log(reg2.test("")); // false
- X? Match the previous pattern x ---> 0 or 1 time. Equivalent to {0,1}
// ? 只允许a出现1次或0次
var reg3 = new RegExp(/^a?$/);
console.log(reg3.test("a")); // true
console.log(reg3.test("")); // true
console.log(reg3.test("aaa")); // false
- X{n} n is a non-negative integer. Match when the previous pattern x is repeated n times
// {3} 允许重复3次
var reg4 = new RegExp(/^a{3}$/);
console.log(reg4.test("a")); // false
console.log(reg4.test("")); // false
console.log(reg4.test("aaa")); // true,
console.log(reg4.test("aaaa")); // false
- X{n,} n is a non-negative integer. Matches when the previous pattern x repeats at least n times.
// {3,} 允许重复出现3次或3次以上多次
var reg5 = new RegExp(/^a{3,}$/);
console.log(reg5.test("a")); // false
console.log(reg5.test("")); // false
console.log(reg5.test("aaa")); // true
console.log(reg5.test("aaaa")); // true
- X{n,m} n and m are non-negative integers. The previous pattern x repeats at least n times, and matches at most m times.
// {3,6} 允许重复出现3次-6次之间,也就是>=3且<=6
var reg6 = new RegExp(/^a{3,6}$/);
console.log(reg6.test("a")); // false
console.log(reg6.test("aaaa")); // true
console.log(reg6.test("aaaaaa")); // true
console.log(reg6.test("aaaaaaa")); // false
Case: Use regular expressions to match 11 valid mobile phone numbers, QQ numbers, ID numbers, and password verification
1. Match QQ number
//匹配QQ号 用到精准匹配^ $
//不能以数字0开头 只能由数字组成 长度为5-11位
var regQQ = /^[1-9]\d{4,10}$/; //因为^[1-9] 已经占了一位,所以后面的数的长度范围就为{4,10}
console.log(regQQ.test('12311111224')); //true
console.log(regQQ.test('02311111224')); //false
console.log(regQQ.test('0588247')); //false
2. Match ID number
//身份证号码是18位的
// 不能以数字0开头,只能由数字组成,最后一位可能是x,X,数字
var reg = /^[1-9]\d{16}(x|X|\d)$/; //可用到选择分组我觉得
//又或者写成var reg = /^[1-9]\d{16}[xX\d]$/; 也可
console.log(reg.test('450521196767676776')); //true
console.log(reg.test('45052119991003845X')); //true
console.log(reg.test('0450521199910022227')); //false
3. Verify whether it is a valid 11-digit mobile phone number?
- Start with 1
- The second digit is any one of 3, 4, 5, 7, 8
- Finally, it ends with 9 integers from 0-9
// 以1为开头
//第二位为3,4,5,7,8中的任意一位
// 最后以0-9的9个整数结尾
var myreg = /^[1][3,4,5,7,9][0-9]{9}$/; // \d 等效于 [0-9]
console.log(myreg.test('17878273092')); //true
4. Password verification
Matching password, must contain uppercase, lowercase and numbers, and special characters (!,@,#,%,&), and more than 6 digits
//匹配密码,必须包含大写,小写和数字,和特殊字符
(!,@,#,%,&),且大于6位
var pattern = /(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9])(?=.*[!|@|#|%|&])[A-Za-z0-9!@#%&]{6,}/
console.log(pattern.test('Ac3!56'),'password'); //true
Repeat mode (greedy mode and non-greedy mode)
- The most straightforward understanding is that greedy mode is to match as many as possible, and non-greedy mode is to match as few as possible.
1) Greedy mode: Match as much as possible (first take the maximum number of matches as a group for matching), when matching the remaining strings, it will continue to try new matches until it fails to match, which is the default mode
// 对字符串"123456789",匹配其中的数字3-6次:\d{3,6},先匹配数字出现6次的字符串(123456),
//然后再从剩余字符串(789)中匹配出现数字3次的情况,剩余字符若没有出现数字3次则停止匹配.
var str = "123456789";
var reg = /\d{3,6}/g;
console.log(reg.exec(str)); //[ '123456', index: 0, input: '12345678', groups: undefined ]
console.log(reg.exec(str)); // [ '789', index: 6, input: '123456789', groups: undefined ]
console.log(reg.exec(str)); // null
2) Non-greedy mode: Match as few as possible (take the least number of matches each time as a group for matching), until no match is found
use after the quantifier?
// 对字符串"123456789",匹配其中的数字3-6次:\d{3,6},先匹配数字出现3次的字符串(123456),
//然后再从剩余字符串(456789)中匹配出现数字3次的情况,剩余字符若没有出现数字3次则停止匹配.
var str = "123456789";
var reg = /\d{3,6}?/g;
console.log(reg.exec(str)); //[ '123', index: 0, input: '123456789', groups: undefined ]
console.log(reg.exec(str)); // [ '456', index: 3, input: '123456789', groups: undefined ]
console.log(reg.exec(str)); // [ '789', index: 6, input: '123456789', groups: undefined ]
Selection, grouping, reference
- choose
The character "|" is used to separate the characters for selection. The matching order of the choices is from left to right, knowing that a match is found, if the left choice matches, the right match is ignored, even if it produces better Match.
var reg = /html|css|js/
console.log(reg.exec('qweqwehtmlcss')); // html
- Grouping
The following regular expression can match'briupbriupbriup'
这里有圆括号包裹的一个小整体成为分组。
var reg = /(briup){3}/;
Candidate: There can be multiple candidate expressions in a group, separated by |:
var reg = /I Like (basketball|football|table tennis)/
console.log(reg.test('I Like basketball')); //true
console.log(reg.test('I Like football')); //true
console.log(reg.test('I Like table tennis')); //true
Capture and quote: The string matched (captured) by the regular expression will be temporarily stored. Among them, the strings captured by the packet will be numbered starting from 1, so we can quote these strings:
var reg = /(\d{4})-(\d{2})-(\d{2})/
var date = '2021-08-29'
reg.test(date)
// 捕获之前要先test/exec
//$1引用了第一个被捕获的串,$2是第二个,依次类推。
console.log(RegExp.$1); //2021
console.log(RegExp.$2); //08
console.log(RegExp.$3); //29
Nested packet capture
If you encounter a nested group similar to /((apple) is (a (fruit)))/, what is the order of capture?
The rule is to capture in the order in which the opening parenthesis appears, from left to right, capture when encountering the opening parenthesis
var reg = /((apple) is (a (fruit)))/
var str = "apple is a fruit"
reg.test(str) // true
RegExp.$1 // apple is a fruit
RegExp.$2 // apple
RegExp.$3 // a fruit
RegExp.$4 // fruit
- Quote
References can also be made in regular expressions, which is called backreferences:
//\1引用了第一个被分组所捕获的串,换言之,表达式是动态决定的。
var reg = /(\w{3}) is \1/ //就是\w{3}和\1对等时才为true
console.log(reg.test('kid is kid')); // true
console.log(reg.test('dik is dik')); // true
console.log(reg.test('kid is dik')); // false
console.log(reg.test('dik is kid')); // false
Note that , if the number is out of range, it will be treated as an ordinary expression:
var reg = /(\w{3}) is \6/; //编号越界了
reg.test( 'kid is kid' ); // false
reg.test( 'kid is \6' ); // true
String support for regular expressions
- search ---->> Find whether there is a string matching regular in the string, and return the index value
var str = 'hello world hello'
var regSea = /world/;
var reg2 = /hello/g;
console.log(regSea.exec(str)); //[ 'hello', index: 0, input: 'hello world hello', groups: undefined ]
console.log(str.search(regSea)); //6 //匹配到返回索引值
console.log(str.search(reg2)); //0
- match ---->> matches the regular expression string in the string, and returns a array of
Match the regular expression string in the string, and return a array the string, which includes the string content , position
If the global match is set return all string arrays that conform to the regular expression at one time
If grouping is added, it will return the string that meets the requirements and grouping , but if global matching is at the same time, 1613b5a3853646 will not add grouping content
//match
// 匹配字符串中符合正则表达式的字符串,并返回该字符串的一个**数组**,其中包括字符串**内容**、**位置**
// 如果正则设置全局匹配,则**一次性返回所有**符合正则表达式的字符串数组
// 如果其中添加了分组,返回符合要求的字符串以及**分组**的一个数组,但如果同时开启全局匹配则**不会在数组中添加
var str = 'hello world hello';
var reg1 = /hello/;
var reg2 = /hello/g;
var reg3 = /(he)llo/;
var reg4 = /(he)llo/g;
// 匹配字符串中符合正则表达式的字符串,并返回该字符串的一个数组,其中包括字符串内容、位置
console.log(str.match(reg1)); // [ 'hello', index: 0, input: 'hello world hello', groups: undefined ]
// 如果正则设置全局匹配,则一次性返回所有符合正则表达式的字符串数组
console.log(str.match(reg2)); // [ 'hello', 'hello' ]
// 如果其中添加了分组,返回符合要求的字符串以及分组的一个数组
console.log(str.match(reg3));
// [
// 'hello',
// 'he',
// index: 0,
// input: 'hello world hello',
// groups: undefined
// ]
// 如果同时开启全局匹配则不会在数组中添加分组内容
console.log(str.match(reg4)); // [ 'hello', 'hello' ]
- split ---->>Split the string in some form and return an array
// 以某种形式分割字符串 split()
var str = "terry134briup156lisi12zhangsan";
// 当数字出现一次或多次时
var reg = /\d+/; //匹配到数字时就切割开来
var result = str.split(reg);
console.log(result); // [ 'terry', 'briup', 'lisi', 'zhangsan' ]
例如:
// 以某种形式分割字符串 split()
var str = "world";
var reg = /\s?/; //以Unicode空格符形式切割 其实字符串的每两个单字符之间都默认存在一个空字符 所以才会切割成功
var result = str.split(reg);
console.log(result); // [ 'w', 'o', 'r', 'l', 'd' ]
- replace --->> The content that meets the regular expression conditions will be replaced
//replace 满足正则表达式条件的内容将被替换
var str = 'hello world good place';
var reg = /\bhello\b/;
console.log(str.replace(reg,'go')); //go world good place
Lookahead expression
In the regular expression there is something called look ahead, some call it zero-width assertion:
expression | Name | Description |
---|---|---|
(?=exp) | Looking forward | The position that satisfies the expression exp after the match |
(?!exp) | Negative lookahead | The position that does not satisfy the expression exp after the match |
Looking forward
var str = 'Hello, Hi, I am Hilary.';
var reg = /H(?=i)/g; //从左到右,前一个字符是H,后一个字符是i,那么这个H就会被匹配到,并被T替换
var newStr = str.replace(reg, "T");
console.log(newStr); // Hello, Ti, I am Tilary.
Give another chestnut:
var str='a2*34v8';
//从左到右,每两个字符进行校对,\w相当于[a-zA-Z0-9_ ],
//前一个字符符合\w,后一个字符符合[0-9],那么前一个字符就被替换成X
var result=str.replace(/\w(?=\d)/g,'X');
console.log(result); //X2*X4X8
There is a little story about foresight. . .
In this DEMO, we can see the forward-looking effect, which is also the character "H", but only matches the "H" that immediately follows the "i". It is equivalent to a company reg. At this time, many "H" personnel came to apply, but the reg company put forward a hard requirement that the "i" skill must be mastered, so "Hello" was naturally eliminated. .
Negative lookahead
var str = 'Hello, Hi, I am Hilary.';
var reg = /H(?!i)/g; //跟正向前瞻相反,负向前瞻则是从右到左,前一个字符是H,后一个字符不是i时,那么这个H就会被匹配到,并被T替换
var newStr = str.replace(reg, "T");
console.log(newStr);//Tello, Hi, I am Hilary.
var str='a2*34v8';
var result=str.replace(/\w(?!\d)/g,'X');//[^0-9a-zA-z_ ]
console.log(result) //aX*3XvX
Keep telling the story. . .
In this DEMO, we replaced the previous positive lookahead with a negative lookahead. The meaning of this regularity is to match "H", and cannot be followed by an "i". At this time, "Hello" can successfully apply, because the reg company has modified their recruitment conditions. They said that the "i" technology will damage the company's corporate culture, so we don't want it.
It's finally over. . . . . .
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。