正则表达式在同一行重复单词 [英] Regex repeated words on the same line

查看:36
本文介绍了正则表达式在同一行重复单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正则表达式查找在同一行上重复的单词?我尝试了在 StackOverflow 上找到的一些表达式,如 this,但没有一个能正常工作.

regular expression to find words that are repeated on the same line? I've tried some expressions that I found on StackOverflow as this, but none is working correctly.

我希望我能用一张图片更好地解释我想要达到的结果.感谢您的耐心等待.

I hope I can explain better with an image the result I want to achieve. Thanks for your patience.

推荐答案

此正则表达式将用于查找要突出显示的单词.(Javascript 中的示例,易于在浏览器的 Javascript 控制台中测试.)

This regex will do to find which words you want to highlight. (example in Javascript, easy to test in the browser's Javascript console.)

s = "It's a foo and a bar and a bar and a foo too.";
a = s.match(/\b(\w+)\b(?=.*\b\1\b)/g);

这将返回一个单词数组,可能是同一个单词的多次.

This returns an array of words, possibly mulitple times for the same word.

接下来你可以这样做:

re = new RegExp('\\b(' + a.join('|') + ')\\b', 'g');

这应该足以突出显示所有事件:

and that should suffice to highlight all occurrences:

out = s.replace(re, function(m) { return '<b>' + m + '</b>' });

这篇关于正则表达式在同一行重复单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆