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
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'));
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;
}
}