regex to remove all text before a character

前端 未结 6 1022
孤独总比滥情好
孤独总比滥情好 2020-12-13 06:46

Is there an easy way to remove all chars before a \"_\"? For example, change 3.04_somename.jpg to somename.jpg.

Any suggestions for where t

相关标签:
6条回答
  • 2020-12-13 07:05

    The regular expression:

    ^[^_]*_(.*)$
    

    Then get the part between parenthesis. In perl:

    my var = "3.04_somename.jpg";
    $var =~ m/^[^_]*_(.*)$/;
    my fileName = $1;
    

    In Java:

    String var = "3.04_somename.jpg";
    String fileName = "";
    Pattern pattern = Pattern.compile("^[^_]*_(.*)$");
    Matcher matcher = pattern.matcher(var);
    if (matcher.matches()) {
        fileName = matcher.group(1);
    }
    

    ...

    0 讨论(0)
  • 2020-12-13 07:05

    In Javascript I would use /.*_/, meaning: match everything until _ (including)

    Example:

    console.log( 'hello_world'.replace(/.*_/,'') ) // 'world'
    
    0 讨论(0)
  • 2020-12-13 07:09

    I learned all my Regex from this website: http://www.zytrax.com/tech/web/regex.htm. Google on 'Regex tutorials' and you'll find loads of helful articles.

    String regex = "[a-zA-Z]*\.jpg";
    System.out.println ("somthing.jpg".matches (regex));
    

    returns true.

    0 讨论(0)
  • 2020-12-13 07:20

    Variant of Tim's one, good only on some implementations of Regex: ^.*?_

    var subjectString = "3.04_somename.jpg";
    var resultString = Regex.Replace(subjectString,
        @"^   # Match start of string
        .*?   # Lazily match any character, trying to stop when the next condition becomes true
        _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
    
    0 讨论(0)
  • 2020-12-13 07:29
    ^[^_]*_
    

    will match all text up to the first underscore. Replace that with the empty string.

    For example, in C#:

    resultString = Regex.Replace(subjectString, 
        @"^   # Match start of string
        [^_]* # Match 0 or more characters except underscore
        _     # Match the underscore", "", RegexOptions.IgnorePatternWhitespace);
    

    For learning regexes, take a look at http://www.regular-expressions.info

    0 讨论(0)
  • 2020-12-13 07:29

    no need to do a replacement. the regex will give you what u wanted directly:

    "(?<=_)[^_]*\.jpg"
    

    tested with grep:

     echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
    somename.jpg
    
    0 讨论(0)
提交回复
热议问题