Skip to content

regex

示例

regex match

  • match匹配示例:
js
const str1 = "For more information, see Chapter 3.4.5.1";
const re1 = /see (chapter \d+(\.\d)*)/i;
const found1 = str1.match(re1);
console.log(found1);

const str2 = "For more information, see Chapter 3.4.5.1  see Chapter 3.4.5.1";
const re2 = /see (chapter \d+(\.\d)*)/i;
const found2 = str2.match(re2);
console.log(found2);

const str3 = "For more information, see Chapter 3.4.5.1  see Chapter 3.4.5.1";
const re3 = /see (chapter \d+(\.\d)*)/ig;
const found3 = str3.match(re3);
console.log(found3);

模版字符串

js
function render(template, context) {
  return template.replace(/\{\{(.*?)\}\}/g, (match, key) => context[key]);
}
const template = "{{name}}很厉name害,才{{age}}岁";
const context = { name: "jawil", age: "15" };
console.log(render(template, context));

其它示例

js

regex = /\s+/g

const word = "afa afaf afafaf   afaf"

const result = word.split(regex)
console.log(result)

// \s空格, \S非空格
// \d数字, \D非数字
// \w单词, \W非单词
// /^ $/ 以什么开头,以什么结尾
// /g全局匹配, /i忽略大小写




// https://www.cnblogs.com/sylys/p/11629399.html

// 匹配日期
var dateStr = '2015-10-10';
var reg = /^\d{4}-\d{1,2}-\d{1,2}$/
console.log(reg.test(dateStr));


// 1. 提取工资
var str = "张三:1000,李四:5000,王五:8000。";
var array = str.match(/\d+/g);
console.log(array);

// 2. 提取email地址
var str = "[email protected],[email protected] [email protected] 2、[email protected] [email protected]...";
var array = str.match(/\w+@\w+\.\w+(\.\w+)?/g);
console.log(array);

// 3. 分组提取  
// 3. 提取日期中的年部分  2015-5-10
var dateStr = '2016-1-5';
// 正则表达式中的()作为分组来使用,获取分组匹配到的结果用Regex.$1 $2 $3....来获取
var reg = /(\d{4})-(\d{1,2})-\d{1,2}/;
if (reg.test(dateStr)) {
  console.log(RegExp.$1);
//   console.log(RegExp.$2);
// console.log(dateStr.match(reg));
}


// 4. 提取邮件中的每一部分
var reg = /(\w+)@(\w+)\.(\w+)(\.\w+)?/;
var str = "[email protected]";
if (reg.test(str)) {
  console.log(RegExp.$1);
  console.log(RegExp.$2);
  console.log(RegExp.$3);
}


// 1. 替换所有空白
var str = "   123AD  asadf   asadfasf  adf ";
str = str.replace(/\s/g,"xx");
console.log(str);

// 2. 替换所有,|,
var str = "abc,efg,123,abc,123,a";
str = str.replace(/,|/g, ".");
console.log(str);

console.log('--------------')

var str1 = "afafa-afafasfaf"
var regex1 =/\w+/g
console.log(str1.match(regex1))