在Java中查找Regex的最新索引

时间:2010-04-01 13:48:49

标签: java regex

我有一个字符串%/O^/O%/O。我想找到最后一个/分割字符串。第一次尝试是:\/[POL]$但是它将"O"包含在内,这是显而易见的。有人提示吗?

7 个答案:

答案 0 :(得分:10)

/(?=[^/]*$)

将匹配/以后不再有/的{​​{1}}。要拆分,请使用

String[] splitArray = subjectString.split("/(?=[^/]*$)");

答案 1 :(得分:9)

我同意使用标准的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.
 * 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);
}

此外,可以通过首先反转输入字符串,然后获取第一组的结束索引(而不是遍历所有组)来使此方法更快。

但要做到这一点,你也必须扭转这种模式;在某些情况下(例如我搜索单个字符的情况)可能很简单,但在其他情况下可能会有问题。

答案 2 :(得分:4)

你需要使用正则表达式吗? String。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);

答案 3 :(得分:4)

虽然你给出的例子没有,但核心问题是好的 需要它。 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();
}

如果您需要最后一个索引:

/**
* 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();
}

答案 4 :(得分:2)

如果你想要的只是找到一个字符的最后一个实例,那么regex就是矫枉过正,你应该只使用String的lastIndexOf

int pos = myString.lastIndexOf('/');

答案 5 :(得分:0)

        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());

答案 6 :(得分:0)

参考: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;
}