Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match only if two sequences are identical

Tags:

java

regex

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?

like image 352
Tim B Avatar asked Dec 24 '22 12:12

Tim B


1 Answers

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

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

DEMO

like image 122
Avinash Raj Avatar answered Jan 05 '23 05:01

Avinash Raj