有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!


共 (3) 个答案

  1. # 1 楼答案

    基于@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;
    }
    
  2. # 2 楼答案

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

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

    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
        }
    

    或者

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