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

javaScript经典系列之正则表达式 #18

Open
wangzhenggui opened this issue Apr 17, 2019 · 0 comments
Open

javaScript经典系列之正则表达式 #18

wangzhenggui opened this issue Apr 17, 2019 · 0 comments

Comments

@wangzhenggui
Copy link
Owner

wangzhenggui commented Apr 17, 2019

正则表达式小结

实例化一个RegExp对象有俩种方式

  1. /^$/
  2. new RegExp()
第一种方式
 var reg = /\bis\b/;
 var str = 'This is abc,This is def';
 str.replace(reg,'IS');

 var reg = /\bis\b/g;
 var str = 'This is abc,This is def';
 str.replace(reg,'IS');

 第二种方式
 var reg = new RegExp('\\bis\\b')
 var str = 'This is abc,This is def';
 str.replace(reg,'IS');

 var reg = new RegExp('\\bis\\b','g') 
 var str = 'This is abc,This is def';
 str.replace(reg,'IS');

/^$/ 和 /^$/g 这俩种方式的区别? 后面一种方式表示匹配全文,前面只会匹配第一项

g标示全局标示
i表示忽略大小写
m表示多行搜索

使用时可以连在一起使用;例如 /\bis\b/gi 表示全局搜索并且忽略大小写

###常用元字符

\d 数字标示
\D 除数字以外
\w 单词表示 包括字母数字下划线
\W 除了上面\w以外的
\s 空格
\S 除了空格
\b 单词边界
\B 非单词边界 【单词边界分左右】 例如想匹配This中的is \Bis\b
{} 量词
() $1 分组
[] 或者

^ 开头 取反意思
$ 结尾
. 任意字符

  • 任意个字符 表示量词
    ? 0次或一次
  • 最少一次
  • 任意次包括0次

贪婪模式、非贪婪模式
贪婪模式是尽可能匹配多的元素
非贪婪模式匹配最少量的元素,只要在量词后面加问号就可以了
例子:
'a12345'.match(/[a-z]\d{3,6}/)
贪婪模式下匹配结果为:'a12345'
'a12345'.match(/[a-z]\d{3,6}?/)
非贪婪模式下匹配结果为:'a123'

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