Yuchen Huang
Yuchen Huang

Reputation: 311

Java regular expression match two same number

I want to use RE to match the file paths like below:

../90804/90804_0.jpg
../89246/89246_8.jpg
../89247/89247_14.jpg

Currently, I use the code as below to match:

Pattern r = Pattern.compile("^(.*?)[/](\\d+?)[/](\\d+?)[_](\\d+?).jpg$");
Matcher m = r.matcher(file_path);

But I found it will be an unexpected match like for:

../90804/89246_0.jpg

Is impossible in RE to match two same number?

Upvotes: 1

Views: 643

Answers (3)

SL5net
SL5net

Reputation: 2556

this regEx ^(.*)\/(\d+?)\/(\d+?)_(\d+?)\.jpg$

is matching stings like this:

../90804/90804_0.jpg
../89246/89246_8.jpg
../89247/89247_14.jpg

into 4 parts.

See example Result:

enter image description here

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626845

You may use a \2 backreference instead of the second \d+ here:

s.matches("(.*?)/(\\d+)/(\\2)_(\\d+)\\.jpg")

See the regex demo. Note that if you use matches method, you won't need ^ and $ anchors.

Details

  • (.*?) - Group 1: any 0+ chars other than line break chars as few as possible
  • / - a slash
  • (\\d+) - Group 2: one or more digits
  • / - a slash
  • (\\2) - Group 3: the same value as in Group 2
  • _ - an underscore
  • (\\d+) - Group 4: one or more digits
  • \\.jpg - .jpg.

Java demo:

Pattern r = Pattern.compile("(.*?)/(\\d+)/(\\2)_(\\d+)\\.jpg");
Matcher m = r.matcher(file_path);
if (m.matches()) {
    System.out.println("Match found");
    System.out.println(m.group(1));
    System.out.println(m.group(2));
    System.out.println(m.group(3));
    System.out.println(m.group(4));
}

Output:

Match found
..
90804
90804
0

Upvotes: 3

anubhava
anubhava

Reputation: 785156

You can use this regex with a capture group and back-reference of the same:

(\d+)/\1

RegEx Demo

Equivalent Java regex string will be:

final String regex = "(\\d+)/\\1";

Details:

  • (\d+): Match 1+ digits and capture it in group #1
  • /: Math literal /
  • \1: Using back-reference #1, match same number as in group #1

Upvotes: 3

Related Questions