Can Java String.indexOf() handle a regular expression as a parameter?
I want to capture the index of a part开发者_StackOverflowicular 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('|"|)
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();
}
It's a two-step approach. First, find a match for your pattern, then (second) use Matcher#start
to get the position of the matching String in the content String.
Pattern p = Pattern.compile(myMagicPattern); // insert your pattern here
Matcher m = p.matcher(contentString);
if (m.find()) {
int position = m.start();
}
Based on @Andreas Dolk's answer, wrapped in copy and paste ready code:
/**
* Index of using regex
*/
public static int indexOfByRegex(CharSequence regex, CharSequence text) {
return indexOfByRegex(Pattern.compile(regex.toString()), text);
}
/**
* Index of using regex
*/
public static int indexOfByRegex(Pattern pattern, CharSequence text) {
Matcher m = indexOfByRegexToMatcher(pattern, text);
if ( m != null ) {
return m.start();
}
return -1;
}
/**
* Index of using regex
*/
public static Matcher indexOfByRegexToMatcher(CharSequence regex, CharSequence text) {
return indexOfByRegexToMatcher(Pattern.compile(regex.toString()), text);
}
/**
* Index of using regex
*/
public static Matcher indexOfByRegexToMatcher(Pattern pattern, CharSequence text) {
Matcher m = pattern.matcher(text);
if ( m.find() ) {
return m;
}
return null;
}
精彩评论