[英]Matching the same word twice with a regular expression, not caring what the word is
Take the following input: 请参考以下内容:
foo.foo aefhiuafhiauefheiauh bar.bar jgoeiajgoieajogiae baz.foo ogiejaogijaeoigjea
Say I want to match xx
where x is the same both sides of the dot. 假设我想匹配
xx
,其中x是点的两侧相同。 So I don't want to match xy
. 所以我不想匹配
xy
。 So with the example input, I'd get foo.foo
, bar.bar
and not baz.foo
所以使用示例输入,我会得到
foo.foo
, bar.bar
而不是baz.foo
What I want to do is something like 我想做的就像是
(\w+)\.$1
But of course that doesn't work. 但当然这不起作用。
Is this possible in any sane way with a regex, or should I be matching xy
and handling the comparison of x
and y
in code? 这是否可以使用正则表达式以任何理智的方式,或者我应该匹配
xy
并处理代码中的x
和y
的比较?
For the sake of the question, assume I'm using the Javascript regex engine. 为了这个问题,假设我使用的是Javascript正则表达式引擎。
Try this: 试试这个:
/(\w+)\.\1/g
Tested on http://regexpal.com/ and works. 在http://regexpal.com/上测试并且有效。
Edit: added global modifier like TomTom correctly suggests. 编辑:添加全局修饰符,如TomTom正确建议。
应该与全球!
/(\w+)\.\1/g;
I'm providing an adaptation to the accepted answer for people using Visual Studio 2017 to find the same variable name repeated in the same line. 我正在为使用Visual Studio 2017的用户找到在同一行中重复的相同变量名称的人们接受的答案进行调整。
The search I used is: 我用的搜索是:
(\w+) = \1 [&]
I was searching for VB string concatenations where I want to consider replacing them with either stringbuilder or the simplified &= operator so I wanted to replace: 我正在寻找VB字符串连接,我想考虑用stringbuilder或简化的&=运算符替换它们,所以我想要替换:
MyString = MyString & something
with 同
MyString &= something
The expression works with find all so I was able to find all instances 该表达式与find all一起使用,因此我能够找到所有实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.