Find Last Index Of by Regex in Java

后端 未结 7 1101
梦如初夏
梦如初夏 2021-01-17 17:32

i have a string %/O^/O%/O. I want to find the last / to split the string. First attemp was: \\/[POL]$ but that gets it inclusive the \"O\"

7条回答
  •  醉话见心
    2021-01-17 18:26

    I agree that using the standard String.lastIndexOf() method is your best course of action, but I have recently had use for the Regex part (namely, I wanted to find the last non-alphanumeric character in a string).

    I ended up writing it myself, and thought to share, in hopes that it would serve to help others:

    /**
     * Indicates that a String search operation yielded no results.
     */
    public static final int NOT_FOUND = -1;
    
    /**
     * Version of lastIndexOf that uses regular expressions for searching.
     * By Tomer Godinger.
     * 
     * @param str String in which to search for the pattern.
     * @param toFind Pattern to locate.
     * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
     */
    public static int lastIndexOfRegex(String str, String toFind)
    {
        Pattern pattern = Pattern.compile(toFind);
        Matcher matcher = pattern.matcher(str);
    
        // Default to the NOT_FOUND constant
        int lastIndex = NOT_FOUND;
    
        // Search for the given pattern
        while (matcher.find())
        {
            lastIndex = matcher.start();
        }
    
        return lastIndex;
    }
    
    /**
     * Finds the last index of the given regular expression pattern in the given string,
     * starting from the given index (and conceptually going backwards).
     * By Tomer Godinger.
     * 
     * @param str String in which to search for the pattern.
     * @param toFind Pattern to locate.
     * @param fromIndex Maximum allowed index.
     * @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
     */
    public static int lastIndexOfRegex(String str, String toFind, int fromIndex)
    {
        // Limit the search by searching on a suitable substring
        return lastIndexOfRegex(str.substring(0, fromIndex), toFind);
    }
    

    Also, it may be possible to make this method faster by first reversing the input string, then taking the ending index of the first group (rather than going over all the groups).

    But to do that you would have to reverse the pattern as well; that can be simple in some cases (like my case of searching for a single character), but may prove problematic in others.

提交回复
热议问题