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
"
*/

最新文章

  1. 重载运算符:类成员函数or友元函数
  2. Linq(一)
  3. EasyUi&ndash;8.datebox赋值的问题
  4. mvc-9测试和调试
  5. python类——黑板客老师课程学习
  6. 用Word收集网页中的内容,用文档结构图整理
  7. 自定义Writable、RawComparatorWritable、comparators(转)
  8. MS CRM 2011的自定义和开发(11)——插件(plugin)开发(四)
  9. Inside of Jemalloc
  10. java-生产者消费者模式
  11. 移动web前端开发时注意事项(转)
  12. iOS深浅拷贝
  13. Rocketlab公司火箭Electron介绍
  14. 使用ssh登录kali
  15. CSS面试复习(三):预处理器、工程化方案、三大框架中的CSS
  16. 【转】comparable Interface
  17. 20155219 2016-2017-2 《Java程序设计》第6周学习总结
  18. oracle 操作,偶尔记一下
  19. oj错误之char型超出范围
  20. 启用sa账号

热门文章

  1. 在 VS2008 下操作 Excel 的方法总结
  2. javaweb 学习的好地方
  3. 前端--关于HTML
  4. Android SQLite API的使用(非原创)
  5. #JavaScript对象与继承
  6. Light oj 1030 二分查找
  7. phantomjs初入门
  8. Servlet接收JSP参数乱码问题解决办法
  9. Java中读取文件
  10. iPhone 和Android应用,特殊的链接:打电话,短信,email;