-1

Can we use regexp for indexof() method of String. If so how

According to my knowledge this should print 1 but it
prints "-1"

 System.out.println("hello".indexOf("[e]"));

Can some one please explain

Dee_wab
  • 1,171
  • 1
  • 10
  • 23

2 Answers2

0

According to documentation there is no version of indexof that accepts regex. It is either a char or a String.

int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.
int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.

According to this your code should be

System.out.println("hello".indexOf('e'));
Moti Korets
  • 3,738
  • 2
  • 26
  • 35
0

indexOf simply returns the index of the first occurrence. We can simulate this behaviour with regex easily.

Example:

Matcher m = Pattern.compile("[e]").matcher("Hello");
if (m.find()) {
    System.out.println(m.start());
}

You can put this into a method:

private static int indexOf(String s, String pattern) {
    Matcher m = Pattern.compile(pattern).matcher(s);
    if (m.find()) {
        return m.start();
    } else {
        return -1;
    }
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313