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('|"|)
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.
The indexOf() method returns the position of the first occurrence of specified character(s) in a string.
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.
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.
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With