0

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));
}
1
  • you need to use find function. Commented Feb 25, 2015 at 14:07

4 Answers 4

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

or better if (m.matches())
why do you call find() into while loop? It is enought to call it once.
1

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

Comments

0

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.