Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

正则表达式 #11

Open
george-wq opened this issue Aug 25, 2019 · 0 comments
Open

正则表达式 #11

george-wq opened this issue Aug 25, 2019 · 0 comments

Comments

@george-wq
Copy link
Owner

george-wq commented Aug 25, 2019

正则表达式

REGEXP对象, 实例化RegExp对象

  1. 字面量
var reg = /\bis\b/g;
'He is a boy, This is a dog'.replace(reg, 'IS');
  1. 构造函数
var reg = new RegExp(/\bis\b/, 'g');
'He is a boy, This is a dog'.replace(res, 'IS');
  1. 修饰符
g global全文搜索,不添加,搜索到第一个匹配停止
i ignore case 忽略大小写,默认大小写敏感
m multiple lines 多行搜索

元字符

正则表达式由两种基本字符类型组成:
原义文本字符
元字符

元字符是在正则表达式中有特殊含义的非字母字符

字符类

字符类 [abc]

字符类取反 [^abc]

范围类 [a-z]

'a1s3r4'.replace(/[a-z]/g, 'Q');

预定义类及边界

. 	任意字符
\d  匹配一个数字字符
\D	匹配一个非数字字符。等价于[^0-9]
\s 	空白符
\S 	非空白符
\w  匹配包括下划线的任何单词字符。类似但不等价于“[A-Za-z0-9_]”,这里的"单词"字符使用Unicode字符集。
\W	匹配任何非单词字符。等价于“[^A-Za-z0-9_]”
^   以xxx开始
$   以xxx结束
\b  匹配一个单词的边界 
\B  匹配非单词边界

量词

? 	   出现零次或一次
+ 	   出现一次或多次
*	   出现零次或多次(任意次)
{n}		
{n,m}
{n,}

正则贪婪模式与非贪婪模式

// 贪婪模式:取最大的范围
'12345678'.replace(/\d{3,6}/, 'X');  // "X78"

// 非贪婪模式: 让正则表达式尽可能少的匹配,一旦成功匹配不在继续尝试, 就是在量词后加上? 即可
'12345678'.replace(/\d{3,6}?/g, 'X');  // "XX78"

分组

// 匹配字母与数字连续三次
'a1b2c3d4'.replace(/([a-z]\d){3}/, 'X');   // "Xd4"

// | 或
'BryonserBryenser'.replace(/Bry(on|en)ser/g, 'X');

// 反向引用 用$1 $2 $3 ...来捕获里面的内容
'2019-10-19'.replace(/(\d{4})-(\d{2})-(\d{2})/g, '$2/$3/$1'); // "10/19/2019"

// 忽略分组 => 只匹配不捕获
// 不希望捕获某些分组,只需要在分组内加上?:就可以
'2019-10-19'.replace(/(?:\d{4})-(\d{2})-(\d{2})/g, '$1/$2');   // "10/19"

前瞻

// 字符串后+数字
'a2*v3fg'.replace(/\w(?=\d)/g, 'X');  // "X2*X3fg"

// 数字后+字符
'a2*v3fg'.replace(/(?=\d)\w/g, 'X');  // "aX*vXfg"

对象属性

global: 是否全文搜索,默认false

ignore case: 是否大小写敏感,默认是false

multiple: 多行搜索,默认值false

lastIndex: 是当前表达式匹配内容的最后一个字符的下一个位置

source: 正则表达式的文本字符串

字符串对象方法

// search
'aaaa1'.search('1');
'aaaa1'.search(1);
'aaaa1'.search(/1/);

// match
var str = '1a2c4f5t';
var reg = /\d(\w)\d/;
var list = str.match(reg);  // ["1a2", "4f5"]

// split
'a1b2c3d4e5t|d|u'.split(/\d/g)  // ["a", "b", "c", "d", "e", "t|d|u"]
'a1b2c3d4e5t|d|u'.split(/[\d|]/g)  // ["a", "b", "c", "d", "e", "t", "d", "u"]

// replace
// function会在每次匹配替换的时候调用,有四个参数
// 1.匹配字符串
// 2.正则表达式分组内容,没有分组则没有该参数
// 3.匹配项在字符串中的index
// 4.原字符串
String.prototype.replace(str, replaceStr)
String.prototype.replace(reg, replaceStr)
String.prototype.replace(reg, function)

'a1b1c1'.replace('a', '2') // "22b2c2"
'a1b1c1'.replace(/1/g, '2') // "a2b2c2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant