我有一根绳子%/O^/O%/O
。我想找到最后一个 / 来分割字符串。第一次尝试是:\/[POL]$
但这让它包含了"O"
这是显而易见的。有人给点建议吗?
我同意使用标准 String.lastIndexOf() 方法是最好的做法,但我最近使用了 Regex 部分(即,我想找到字符串中的最后一个非字母数字字符)。
我自己写了它,并想与大家分享,希望它能对其他人有所帮助:
/**
* 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.
*
* @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).
*
* @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);
}
此外,通过首先反转输入字符串,然后获取第一组的结束索引(而不是遍历所有组),可以使此方法更快。
但要做到这一点,你也必须扭转这种模式;在某些情况下这可能很简单(例如我搜索单个字符的情况),但在其他情况下可能会出现问题。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)