简体   繁体   中英

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. So I don't want to match xy . So with the example input, I'd get foo.foo , bar.bar and not 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?

For the sake of the question, assume I'm using the Javascript regex engine.

Try this:

/(\w+)\.\1/g

Tested on http://regexpal.com/ and works.

Edit: added global modifier like TomTom correctly suggests.

应该与全球!

/(\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.

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:

MyString = MyString & something

with

MyString &= something

The expression works with find all so I was able to find all instances

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM