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

正则例子 #6

Open
nianxiongdi opened this issue Aug 6, 2019 · 0 comments
Open

正则例子 #6

nianxiongdi opened this issue Aug 6, 2019 · 0 comments

Comments

@nianxiongdi
Copy link
Owner

nianxiongdi commented Aug 6, 2019

变成驼峰式

let str = "the-first-name"; //变成thefFirstName
 
let reg = /-(\w)/g;
// 匹配的内容  替换成分组的内容
// console.log( str.replace(reg,  "$1")); // $1 代表引用第一个分组
//


console.log( str.replace(reg,  function($, $1) { // $代表当前匹配的内容, $1代表第一个分组的内容  $2代表第二个分组的内容
    // function 匹配几次,执行几次
    return $1.toUpperCase();
})); // $1 代表引用第一个分组
//thefFirstName

正向断言 - 只是判断,不做匹配

// 正向预查 正向断言
var str1 = "abaaaa"; 
var reg1 = /a(?=b)/g // 代表a后面紧跟着b,b只是修饰符号,不是匹配字符
console.log(str1.match(reg1));// a

reg1 = /a(?!b)/g // 代表a后面不是b,b只是修饰符号,不是匹配字符
console.log(str1.match(reg1));// a

贪婪与非贪婪

// 贪婪匹配 - 尽可能多的匹配
str1 = "aaaaa";
reg1 = /a+/g;
console.log(str1.match(reg1)); // [ 'aaaaa' ]

//非贪婪匹配 - 尽可能少的匹配
// 尽可能的少匹配, 使用?进行实现 非贪婪匹配
reg1 = /a+?/g
console.log(str1.match(reg1)); // 匹配一个 [ 'a', 'a', 'a', 'a', 'a' ]
console.log(str1.match(/a{2,3}?/g)); // 匹配两个 [ 'aa', 'aa' ]

console.log(str1.match(/a??/g)) // [ '', '', '', '', '', '' ]
console.log(str1.match(/a*?/g)) // [ '', '', '', '', '', '' ]


字符串去重

str1 = "aaaaaaaaaaabbbbbbbccccccccccccc"
reg1 = /(\w)\1*/g;
console.log(str1.replace(reg1, "$1")); //abc

数字每三位加点

//每三位加个点
str1 = "10000000000000";

/**
 * /(?=(\B)(\d{3})+$)/g
 *     (\d{3})+$) - 代表从后向前匹配,每三位匹配一个
 *     (?=(\d{3})+$) - 代表空字符后面需要是三位的数字,\d{3})+是匹配规则
 *     (?=(\B)(\d{3})+$) - \B代非单词边界
 * */
reg1 = /(?=(\B)(\d{3})+$)/g

console.log(str1.replace(reg1, "."))//10.000.000.000.000
// console.log(str1.match(reg1)); 

字符串是否含有汉字

function isContainNumber(str) {
    var reg = /\d/g;
    return reg.test(str);
}

console.log(isContainNumber('xy')); // false
console.log(isContainNumber('xy2'));// true

汉字匹配

// 匹配汉字
var regx = /^[\u4e00-\u9fa5]{0,}$/;

str = "大话西游";
console.log(regx.test(str));

加逗号

function format(number) {
    var regx = /\d{1,3}(?=(\d{3})+$)/g;
    return (number + '').replace(regx, '$&,')  // $&表示与regx相匹配的字符串
}
console.log( format('12321321') );

正则表达式

// 数组+字母@域名
/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g.test('nianxiogndi@163.com') // true
/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/g.test('nianxiogndi') // false

// 手机
 /^1[3456789]\d{9}$/.test(phone)

文献

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