[Regular Expressions] Match the Same String Twice
2024-09-04 09:28:44
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 = `<b>Bold</b><i>italics</i>`;
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 = `<b>Bold</b><i>italics</i>`;
var regex = /<(\w+)>(.*)<\/\1>/g; console.log(str.replace(regex, '$2\n')); /*
"Bold
italics
"
*/
最新文章
- 重载运算符:类成员函数or友元函数
- Linq(一)
- EasyUi&ndash;8.datebox赋值的问题
- mvc-9测试和调试
- python类——黑板客老师课程学习
- 用Word收集网页中的内容,用文档结构图整理
- 自定义Writable、RawComparatorWritable、comparators(转)
- MS CRM 2011的自定义和开发(11)——插件(plugin)开发(四)
- Inside of Jemalloc
- java-生产者消费者模式
- 移动web前端开发时注意事项(转)
- iOS深浅拷贝
- Rocketlab公司火箭Electron介绍
- 使用ssh登录kali
- CSS面试复习(三):预处理器、工程化方案、三大框架中的CSS
- 【转】comparable Interface
- 20155219 2016-2017-2 《Java程序设计》第6周学习总结
- oracle 操作,偶尔记一下
- oj错误之char型超出范围
- 启用sa账号