我想捕获Java String中特定正则表达式的索引.该字符串可以用单引号或双引号括起来(有时没有引号).如何使用Java捕获该索引?
例如:
capture String --> class = ('|"|)word('|"|)
Run Code Online (Sandbox Code Playgroud)
Jig*_*shi 43
不.
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
}
Run Code Online (Sandbox Code Playgroud)
要么
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();
}
Run Code Online (Sandbox Code Playgroud)
And*_*s_D 33
这是一个两步走的方法.首先,找到您的模式匹配,然后(第二)用于Matcher#start获取内容String中匹配String的位置.
Pattern p = Pattern.compile(myMagicPattern); // insert your pattern here
Matcher m = p.matcher(contentString);
if (m.find()) {
int position = m.start();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53380 次 |
| 最近记录: |