在 Java 中按正则表达式查找最后一个索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2560780/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Find Last Index Of by Regex in Java
提问by Andreas
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"which is obvious. Has somebody a tip?
我有一个字符串%/O^/O%/O。我想找到最后一个 / 来拆分字符串。第一次尝试是:\/[POL]$但它包含了"O"显而易见的内容。有人有提示吗?
采纳答案by justkt
Do you need to use regular expressions for this? Would String.lastIndexOf("/")work to find the index, and then use String.substring(int start, int end)with the result? Or is your actual data different and more complicated, requiring regular expressions? With what you provided to split the string on the last /, here's code:
你需要为此使用正则表达式吗?将字符串。lastIndexOf("/")工作找到索引,然后使用String.substring(int start, int end)得到结果?或者您的实际数据是否不同且更复杂,需要正则表达式?使用您提供的在最后一个 / 上拆分字符串的内容,代码如下:
int lastSlash = mystring.lastIndexOf("/");
String start = mystring.substring(0, lastSlash);
String end = mystring.substring(lastSlash + 1, mystring.length);
回答by Tim Pietzcker
/(?=[^/]*$)
will match a /that isn't followed by any more /s. To split on it, use
将匹配/后面没有更多/s 的 a。要拆分它,请使用
String[] splitArray = subjectString.split("/(?=[^/]*$)");
回答by Tomer Godinger
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).
我同意使用标准 String.lastIndexOf() 方法是您最好的行动方案,但我最近使用了 Regex 部分(即,我想找到字符串中的最后一个非字母数字字符)。
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.
但是要做到这一点,您还必须扭转模式;在某些情况下这可能很简单(例如我搜索单个字符的情况),但在其他情况下可能会出现问题。
回答by Julian Cochran
The core question is good although the example you gave doesn't need it. Java's indexOf doesn't take regular expressions. Answering just subject part of the question, here's what you would need:
核心问题很好,尽管您给出的示例不需要它。Java 的 indexOf 不接受正则表达式。仅回答问题的主题部分,这是您需要的:
/**
* Version of indexOf that uses regular expressions for the search
* by Julian Cochran.
*/
public static int indexOfRegex(String message, String toFind) {
// Need to add an extra character to message because to ensure
// split works if toFind is right at the end of the message.
message = message + " ";
String separated[] = message.split(toFind);
if (separated == null ||
separated.length == 0 ||
separated.length == 1) {
return -1;
}
return separated[0].length();
}
If you need the last index:
如果您需要最后一个索引:
/**
* Version of lastIndexOf that uses regular expressions for
* the search by Julian Cochran.
*/
public static int lastIndexOfRegex(String message, String toFind) {
// Need to add an extra character to message because to ensure
// split works if toFind is right at the end of the message.
message = message + " ";
String separated[] = message.split(toFind);
if (separated == null ||
separated.length == 0 ||
separated.length == 1) {
return -1;
}
return separated[separated.length - 1].length();
}
回答by M. Jessup
If all you want is to find the last instance of a character regex is overkill, you should just use String's lastIndexOf
如果你只想找到一个字符正则表达式的最后一个实例是矫枉过正,你应该只使用字符串的 lastIndexOf
int pos = myString.lastIndexOf('/');
回答by Ramireddy Chintalapudi
String name ="rami is good boy, and he is working for andorid,is completed";
int lastSlash = name.lastIndexOf("is");
String start = name.substring(0, lastSlash);
String end = name.substring(lastSlash + 1, name.length());
StringBuffer sb = new StringBuffer(name);
sb.replace(start.length(), name.lastIndexOf(end)+1, "");
System.out.println(sb.toString());
回答by qxo
ref: https://github.com/apache/commons-lang/pull/273/files
参考:https: //github.com/apache/commons-lang/pull/273/files
public static int lastIndexOfAnyChar( final CharSequence str,final String searchChars) {
return searchChars == null ? INDEX_NOT_FOUND : lastIndexOfAnyChar(str,searchChars.toCharArray());
}
/**
* <p>Search a CharSequence to find the last index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastIndexOfAnyChar(null, *) = -1
* StringUtils.lastIndexOfAnyChar("", *) = -1
* StringUtils.lastIndexOfAnyChar(*, null) = -1
* StringUtils.lastIndexOfAnyChar(*, []) = -1
* StringUtils.lastIndexOfAnyChar("zzabyycdxx",['z','a']) = 2
* StringUtils.lastIndexOfAnyChar("zzabyycdxx",['b','y']) = 5
* StringUtils.lastIndexOfAnyChar("aba", ['z']) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the last index of any of the chars, -1 if no match or null input
*/
public static int lastIndexOfAnyChar( final CharSequence str,final char... searchChars) {
if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int csLen = str.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = csLast ; i >= 0 ; i--) {
char ch = str.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch) ) {
// ch is a supplementary character
if (searchChars[j + 1] == str.charAt(i + 1)) {
return i;
}
} else {
return i;
}
}
}
}
return INDEX_NOT_FOUND;
}

