Remove part of String following regex match in Java

后端 未结 3 1690
别跟我提以往
别跟我提以往 2020-12-21 02:56

I want to remove a part of a string following what matches my regex.

I am trying to make a TV show organization program and I want to cut off anything in the name f

相关标签:
3条回答
  • 2020-12-21 03:23

    matches matches the entire string, try find()

    You could capture the name as well:

    String name = "a movie S01E02 with some stuff";
    Pattern p = Pattern.compile("(.*[Ss]\\d\\d[Ee]\\d\\d)");
    Matcher m = p.matcher(name);
    
    if (m.find())
        System.out.println(m.group());
    else
        System.out.println("No match");
    

    Will capture and print:

    a movie S01E02

    0 讨论(0)
  • 2020-12-21 03:24

    matches() tries to match the whole string again the pattern. If you want to find your pattern within a string, use find(), find() will search for the next match in the string.

    Your code could be quite the same:

    if(m.find())
        return name.substring(0, m.end());
    
    0 讨论(0)
  • 2020-12-21 03:47

    This should work

    .*[Ss]\d\d[Ee]\d\d
    

    In java (I'm rusty) this will be

    String ResultString = null;
    
    Pattern regex = Pattern.compile(".*[Ss]\\d\\d[Ee]\\d\\d");
    Matcher regexMatcher = regex.matcher("Title S11E11Blah");
    if (regexMatcher.find()) {
        ResultString = regexMatcher.group();
    } 
    

    Hope this helps

    0 讨论(0)
提交回复
热议问题