Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Java String.indexOf() handle a regular expression as a parameter?

Tags:

java

I want to capture the index of a particular regular expression in a Java String. That String may be enclosed with single quote or double quotes (sometimes no quotes). How can I capture that index using Java?

eg:

capture String -->  class = ('|"|)word('|"|) 
like image 779
Roshan Avatar asked Nov 16 '10 12:11

Roshan


People also ask

What does the method indexOf require as a parameter?

The indexOf method takes two parameters: A literal string “Java” whose starting index has to be found and integer type fromindex 10, which specifies the index after which the “Java” string's starting index has to be returned which would be 25 in this case.

What does indexOf () Do Java?

The indexOf() method returns the position of the first occurrence of specified character(s) in a string.

Is indexOf faster than regex?

For just finding a keyword the IndexOf method is faster than using a regular expression. Regular expressions are powerful, but their power lies in flexibility, not raw speed. They don't beat string methods at simple string operations.

What indexOf () will do?

indexOf() The indexOf() method, given one argument: a substring to search for, searches the entire calling string, and returns the index of the first occurrence of the specified substring.


1 Answers

No.

Check source code for verification

WorkAround : Its not standard practice but you can get result using this.

Update:

    CharSequence inputStr = "abcabcab283c";     String patternStr = "[1-9]{3}";     Pattern pattern = Pattern.compile(patternStr);     Matcher matcher = pattern.matcher(inputStr);     if(matcher.find()){      System.out.println(matcher.start());//this will give you index     } 

OR

Regex r = new Regex("YOURREGEX");  // search for a match within a string r.search("YOUR STRING YOUR STRING");  if(r.didMatch()){ // Prints "true" -- r.didMatch() is a boolean function // that tells us whether the last search was successful // in finding a pattern. // r.left() returns left String , string before the matched pattern  int index = r.left().length(); }  
like image 64
jmj Avatar answered Oct 09 '22 10:10

jmj