Java String.indexOf() 可以将正则表达式作为参数处理吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4194310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:25:44  来源:igfitidea点击:

Can Java String.indexOf() handle a regular expression as a parameter?

java

提问by Roshan

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?

我想在 Java 字符串中捕获特定正则表达式的索引。该字符串可以用单引号或双引号括起来(有时没有引号)。如何使用 Java 捕获该索引?

eg:

例如:

capture String -->  class = ('|"|)word('|"|)

采纳答案by Jigar Joshi

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();
} 

回答by Andreas Dolk

It's a two-step approach. First, find a match for your pattern, then (second) use Matcher#startto get the position of the matching String in the content String.

这是一个两步走的方法。首先,为您的模式找到一个匹配项,然后(第二个)用于Matcher#start获取匹配字符串在内容字符串中的位置。

Pattern p = Pattern.compile(myMagicPattern);  // insert your pattern here
Matcher m = p.matcher(contentString);
if (m.find()) {
   int position = m.start();
}