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?

2 Answers 2

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.*',$");
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks.Really clear. Why was that backslash used,just before using \. to match a dot
@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
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'.

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.