28
我想捕获Java字符串中特定正则表达式的索引。该字符串可能包含单引号或双引号(有时不带引号)。我如何使用Java捕获该索引?Java String.indexOf()是否可以将正则表达式作为参数处理?
如:
capture String --> class = ('|"|)word('|"|)
我想捕获Java字符串中特定正则表达式的索引。该字符串可能包含单引号或双引号(有时不带引号)。我如何使用Java捕获该索引?Java String.indexOf()是否可以将正则表达式作为参数处理?
如:
capture String --> class = ('|"|)word('|"|)
没有。
Check source code for verification
解决方法: 它不是标准的做法,但你能得到导致用这个。
更新:
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();
}
这是一个两步走的方法。首先,为您的模式找到一个匹配,然后(秒)使用Matcher#start
获取内容字符串中匹配字符串的位置。
Pattern p = Pattern.compile(myMagicPattern); // insert your pattern here
Matcher m = p.matcher(contentString);
if (m.find()) {
int position = m.start();
}
是否有任何解决方法来实现这个? – Roshan 2010-11-16 12:56:38
@ org.life.java - 你在这里使用什么库?正则表达式不在标准的Java库中。 – 2010-11-16 13:28:18
@Stephen C谢谢,我跟在http://www.javaregex.com/我不确定它是否可靠的lib。我没有亲自使用它,从它的教程 – 2010-11-16 13:32:41