3

I am following the suggestions on the page, check if string ends with certain pattern

I am trying to display a string that is

  • Starts with anything
  • Has the letters ".mp4" in it
  • Ends explicitly with ', (apostrophe followed by comma)

Here is my Java code:

import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.*;

class Ideone
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // your code goes here
        String str = " _file='ANyTypEofSTR1ngHere_133444556_266545797_10798866.mp4',";
        Pattern p = Pattern.compile(".*.mp4[',]$");
        Matcher m = p.matcher(str);
        if(m.find())
            System.out.println("yes");
        else
            System.out.println("no");
    }
}

It prints "no". How should I declare my RegEx?

Community
  • 1
  • 1
Pradeep
  • 1,193
  • 6
  • 27
  • 44

2 Answers2

3

Your character set [',] is checking whether the string ends with ' or , a single time.

If you want to match those character one or more times, use [',]+. However, you probably don't want to use a character set in this case since you said order is important.

To match an apostrophe followed by comma, just use:

.*\\.mp4',$

Also, since . has special meaning, you need to escape it in '.mp4'.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
3

There are several issues in your regex:

  1. "Has the letters .mp4 in it" means somewhere, not necessarily just in front of ',, so another .* should be inserted.
  2. . matches any character. Use \. to match .
  3. [,'] is a character group, i.e. exactly one of the characters in the brackets has to occur.

You can use the following regex instead:

Pattern p = Pattern.compile(".*\\.mp4.*',$");
fabian
  • 80,457
  • 12
  • 86
  • 114
  • Thanks.Really clear. Why was that backslash used,just before using **\.** to match a dot – Pradeep Dec 19 '15 at 16:28
  • @Pradeep: Since `.` in a regex matches any character, but you only want to match the string, if it contains `.mp4` as substring, you need to use `\.mp4`, since otherwise it matches strings containing `xmp4`, but not `.mp4` too. The double backslash just escapes a single backslash – fabian Dec 19 '15 at 16:28