Sammy Pawar
Sammy Pawar

Reputation: 1281

Java Regular Expression string match

I need a help. I am writing a method which will return true if 1954 is in string images/deal/129277/1954-bonus.jpg. I can use string.contains but it won't be accurate always. Instead I want it to return true if 1954 is at exact place. Below sourceKey is images/deal/129277/1954-bonus.jpg and oldImageId is 1954.

Below code is not working.

private boolean keyMatches(String sourceKey, String oldImageId){
    Pattern pattern = Pattern.compile("(.*?)/(\\d+)/(\\d+)-(.*)");
    Matcher matcher = pattern.matcher(sourceKey);
    return oldImageId.equals(matcher.group(3));
}

Upvotes: 0

Views: 62

Answers (4)

Ravi K Thapliyal
Ravi K Thapliyal

Reputation: 51721

Using regex lookahead and String#matches() your function could be a one-liner like

private boolean keyMatches(String sourceKey, String oldImageId){
    return sourceKey.matches(".*/(?!.*/)"+oldImageId+"-.*");
}

I tried the following tests with 1954 placed at various parts of the URL to try fool the regex.

System.out.println(keyMatches("images/deal/129277/1954-bonus.jpg", "1954"));
System.out.println(keyMatches("images/deal/1954-pics/129277-bonus.jpg", "1954"));
System.out.println(keyMatches("123-1954/1954-00/1954/129277-bonus.jpg", "1954"));
System.out.println(keyMatches("images/deal/129277/129277-1954-bonus.jpg", "1954"));

Output :

true
false
false
false

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174874

Seems like you want something like this,

String s = "images/deal/129277/1954-bonus.jpg";
String oldImageId = "1954";
Matcher m = Pattern.compile("(.*?)/(\\d+)/(\\d+)-(.*)").matcher(s);
if(m.find())
{
System.out.println(oldImageId.matches(m.group(3)));
}

Output:

true

Upvotes: 2

AlexR
AlexR

Reputation: 115418

I can see at least one mistake in your code. Matcher does not return any group unless you call find() or match() method before and these methods returned true.

So, your code should be modified as following:

Matcher matcher = pattern.matcher(sourceKey);
return matcher.find() ? oldImageId.equals(matcher.group(3)) : null;

I am leaving it to you to verify that your regex is indeed correct.

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Try something like this :

public static void main(String[] args) {
    String s = "images/deal/129277/1954-bonus.jpg";
    String s1 = "images/deal/1954/1911254-bonus.jpg";
    System.out.println(s.matches(".*/1954\\-.*"));
    System.out.println(s1.matches(".*/1954\\-.*"));
}

O/P:

true
false

Upvotes: 1

Related Questions