Find Last Index Of by Regex in Java

后端 未结 7 1097
梦如初夏
梦如初夏 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:32

    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:

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

提交回复
热议问题