javascript 高级编程系列 - 字符串 & 正则表达式

1. match

str.match(reg)

参数: 一个正则表达式对象,如果reg不是正则表达式对象,则会利用new RegExp(reg) 隐式转换。
返回值:
  1. 正则表达式中如果有g标志,则将返回与完整正则表达式匹配的所有结果,但不会返回捕获组。
  2. 正则表达式中如果没有使用g标志,则仅返回第一个完整匹配及其相关的捕获组(Array)。
     并且返回的项目具有如下的属性。
     - groups:一个命名捕获组对象,其键是捕获组名称,值是捕获组,如果未命名捕获组,则为undefined。
     - index: 匹配结果的开始位置
     - input:搜索的字符串
  3. 如果未找到匹配,则返回null
/** 具有g标志的match方法 **/
const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/gi;
const found = str.match(re);
console.log(found); // [ 'see Chapter 3.4.5.1' ]  // 所有匹配

/** 没有g标志的match方法 **/
const str = 'For more information, see Chapter 3.4.5.1';
const re = /see (chapter \d+(\.\d)*)/i;
const found = str.match(re);
console.log(found); 
// out put blow
[
  'see Chapter 3.4.5.1', //  所有匹配的第一项
  'Chapter 3.4.5.1',    // 第一个捕获组匹配的值
  '.1',  // 第二个捕获组捕获的最后一个值
  index: 22, // 是整个匹配从0开始的索引
  input: 'For more information, see Chapter 3.4.5.1', // 被解析的原始字符串
  groups: undefined
]

2. matchAll

str.matchAll(reg)

参数: 一个正则表达式对象,如果reg不是正则表达式对象,则会利用new RegExp(reg) 隐式转换。
       而且正则表达式必须是设置了全局模式g的正则表达式,否则会抛出异常TypeError。
返回值: 一个迭代器
const regexp = /t(e)(st(\d?))/g;
const str = 'test1test2';
const array = [...str.matchAll(regexp)]; // convert to array
console.log(array[0]);  // expected output: Array ["test1", "e", "st1", "1"]
console.log(array[1]);  // expected output: Array ["test2", "e", "st2", "2"]

注意: 如果只是得到所有的匹配项则使用str.match(pattern/g),
如果是要得到所有匹配项的捕获组的信息则使用str.matchAll(pattern/g)

str.search(reg)

参数: 一个正则表达式对象,如果reg不是正则表达式对象,则会利用new RegExp(reg) 隐式转换。
返回值: 如果匹配成功则返回正则表达式在字符串中首次匹配项的索引,否则返回-1
const str = "hey JudE";
const re = /[A-Z]/g;
const re2 = /[.]/g;
// returns 4, which is the index of the first capital letter "J"
console.log(str.search(re));
// returns -1 cannot find '.' dot punctuation
console.log(str.search(re2)); 

4. replace

str.replace(regexp|substr, newSubStr|function)

参数:
  - regexp (pattern): 一个正则表达式对象,其匹配的值,会被第二个参数返回的值替换。
  - substr (pattern): 字符串,如果匹配会被第二个参数返回的值替换,并且仅第一个匹配项被替换。
  - newSubstr(relacement): 用于替换掉第一个参数匹配部分的字符串,并其其可以内插一些特殊变量。
  - function (replacement): 其返回的新字符串用来替换掉第一个参数匹配的部分。
返回:
  部分或全部由匹配模式所取代的新字符串。

newSubstr 中可以插入的特殊变量

变量名 代表的的值
$$ 插入一个"$"
$& 插入匹配的子串
$` 插入当前匹配的子串左边的内容
$' 插入当前匹配的子串右边的内容
$n 如果第一个参数是正则表达式,则$n是第n个捕获组匹配到内容,如果不存在$n 则会转为字符串$n |
$ Name 为命名分组的名称,如果没有匹配或无此分组,则其值为空字符串, (?) 命名分组
/** 交换字符串中的两个单词 **/
const str = "John Smith";
const newstr = str.replace(/(?<name>\w+)\s(\w+)/, "$2 $$ $1 $3 $<name>");
console.log(newstr);  // Smith $ John $3 John

function 函数作为第二个参数

变量名 代表的的值
match 匹配的子串, 对应为上面的$&
p1, p2, ... 如果第一个参数是正则表达式, 则p1 代表第一个捕获组匹配的内容, 相当于$1
offset 匹配到的子字符串的首字符在原字符中的位置
string 被匹配的原字符串
group 命名捕获组匹配的对象

注意: 具体参数个数取决于replace方法的第一个参数是否是正则表达式以及捕获组的个数等

const str = "John Smith";
const newstr = str.replace(/(?<name>\w+)\s(\w+)/, (match, p1, p2, offset, string, group) => {
  console.log('match: ', match); // match:  John Smith
  console.log('p1: ', p1); // p1:  John
  console.log('p2: ', p2); // p2:  Smith
  console.log('offset: ', offset); // offset:  0
  console.log('string: ', string); // string:  John Smith
  console.log('name: ', group.name); // name:  John
  return `${p2} ${p1}`;
});
console.log(newstr);  // Smith John

5. replaceAll

str.replaceAll(regexp|substr, newSubStr|function)

参数: 其参数与replace方法一样,如果第一个参数使用正则表达式,则必须使用g修饰符,否则程序会抛出类型错误。
返回: 返回一个替换了所有匹配项的新字符串。
const res = 'aabbcc'.replaceAll('b', '.');
console.log(res); // aa..cc

const res = 'aabbcc'.replace(/b/g, '.');
console.log(res); // aa..cc

注意: 由上面的例子可以看出,使用relace方法第一个参数使用正则表达式的全局模式,可以替代replaceAll方法。

6. split

str.split([separator[, limit]])

参数: 
  - separator:指定每一个拆分点的字符串或匹配模式。
    如果separator不指定则返回包含被分隔字符串的数组,
    如果separator为空字符串,则返回包含被分隔字符串每一个字符形成的数组.
  - limit: 限定返回的数量
返回:返回以分隔符拆分的子字符串数组。
/**  使用不捕获组(?:)正则表达式分隔字符串 **/
const names = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
const nameList = names.split(/\s*(?:;|$)\s*/);
// [ 'Harry Trump', 'Fred Barney', 'Helen Rigby', 'Bill Abel', 'Chris Hand', '' ]
console.log(nameList); 

/** 使用limit参数限定返回的数组项 **/
const limitedNameList = names.split(/\s*(?:;|$)\s*/, 5);
// [ 'Harry Trump', 'Fred Barney', 'Helen Rigby', 'Bill Abel', 'Chris Hand']
console.log(limitedNameList);

/** 使用捕获组正则表达式分隔字符串包含分隔符 **/
const nameList = names.split(/\s*(;|$)\s*/);
console.log(nameList);
// [ 'Harry Trump', ';', 'Fred Barney', ';', 'Helen Rigby', ';', 'Bill Abel', ';', 'Chris Hand', '', '' ]

正则表达式相关参考:精通正则表达式 - JavaScript的实现和应用

posted @   箫笛  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示