Tim B
Tim B

Reputation: 41208

Regex to match only if two sequences are identical

Is it possible to write a Java Regex sequence to match two identical sequences within a string. In other words given the string

near[2015-12-1] far[2015-12-1] 

I want to match all strings where the value inside the first square brackets is equal to the one in the second square bracket and the strings outside the square brackets are near[] far[].

near[2015-12-1] far[2015-12-1] MATCH
near[2015-12-3] far[2015-12-1] NO MATCH
near[2015-12-1] far[2014-12-1] NO MATCH
near[2015-12-3] far[2015-12-3] MATCH
foo[2015-12-1] bar[2015-12-1] NO MATCH

Is this possible?

Upvotes: 4

Views: 362

Answers (2)

Dillon Ryan Redding
Dillon Ryan Redding

Reputation: 1243

The regular expression would look something like near\[(.*)\] far\[\1\]. In Java, you'd have something like the following:

Pattern.matches("near\\[(.*)\\] far\\[\\1\\]", "near[2015-12-1] far[2015-12-1]")

or

"near[2015-12-1] far[2015-12-1]".matches("near\\[(.*)\\] far\\[\\1\\]")

Upvotes: 3

Avinash Raj
Avinash Raj

Reputation: 174826

Use capturing group and you should refer those captured characters by back-reference.

"^near\\[(.*?)\\]\\sfar\\[\\1\\]$" 

DEMO

Upvotes: 7

Related Questions