博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Regular Expressions] Match the Same String Twice
阅读量:6593 次
发布时间:2019-06-24

本文共 1109 字,大约阅读时间需要 3 分钟。

Regular Expression Backreferences provide us a method to match a previously captured pattern a second time.

 

For example we have an string, and we want to any word which appear twice at the same time:

var str = "Time is the the most important thing thing."

 

var regex = /(the|thing)\s?/g;

Now it catch 'the' & 'thing', but we only want the first appear one.

 

var regex = /(the|thing)\s?(?=\1)/g;

 

--------------

Code:

var str = `Time is the the most important thing thing.`;var regex = /(the|thing)\s?(?=\1)/g;console.log(str.replace(regex, ''));/*"Time is the most important thing."*/

 

And of course, we can do better:

var regex = /(\w+)\s?(?=\1)/g;

 

----------------------------

 

Also we can use this tech to extract the html content:

var str = `Bolditalics`;

 

So, first we want to match <></>:

 

So, '\1' means capture the first group. '(?=)' means only the first appear one.

var regex = /<(\w+)><\/\1>/g;

 

Then we want to add secod catch group of the content:

var regex = /<(\w+)>(.*)<\/\1>/g;

 

var str = `Bolditalics`;var regex = /<(\w+)>(.*)<\/\1>/g;console.log(str.replace(regex, '$2\n'));/*    "Bold    italics"*/

 

转载地址:http://phdio.baihongyu.com/

你可能感兴趣的文章
Linux开机启动顺序小结
查看>>
C++ 多文件编译简述:头文件、链接性、声明与定义
查看>>
怎么解决MathType希腊字母无法显示的问题
查看>>
SPD4514 Database Technologies and Management
查看>>
【二分图匹配/匈牙利算法】飞行员配对方案问题
查看>>
php小程序登录时解密getUserInfo获取openId和unionId等敏感信息
查看>>
如何给多个子系统设计一个简单通用的权限管理方案?(详细讲解及源代码下载)...
查看>>
linux远程复制/linux远程拷贝/远程上传文件夹 举例
查看>>
进度条(progress)
查看>>
关于宏的一点注意
查看>>
新奇:(nodejs兄弟)用HTML + FLASH +JS 也可以写桌面EXE。
查看>>
透明色设置
查看>>
曾经见过的一篇文章 SQL Server DBA三十问
查看>>
斐波拉契数列的计算方法
查看>>
ID3决策树算法原理及C++实现(其中代码转自别人的博客)
查看>>
文件操作
查看>>
Linux 编译安装Nginx
查看>>
linux下python安装pymssql模块
查看>>
Apache语言支持设置
查看>>
ansible之synchronize模块
查看>>