我想捕获Java String中特定正则表达式的索引。该字符串可以用单引号或双引号括起来(有时没有引号)。如何使用Java捕获该索引?
例如:
capture String --> class = ('|"|)word('|"|)
答案 0 :(得分:40)
否强>
Check source code for verification
WorkAround: 这不是标准做法,但你可以用这个来获得结果。
<强>更新强>
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();
}
答案 1 :(得分:32)
这是一个两步走的方法。首先,找到您的模式的匹配项,然后(第二次)使用Matcher#start
来获取内容字符串中匹配字符串的位置。
Pattern p = Pattern.compile(myMagicPattern); // insert your pattern here
Matcher m = p.matcher(contentString);
if (m.find()) {
int position = m.start();
}
答案 2 :(得分:0)
基于@Andreas Dolk 的回答,包含在复制和粘贴就绪代码中:
/**
* 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;
}