亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

使用正則表達式獲取字符串中模式的索引

使用正則表達式獲取字符串中模式的索引

牧羊人nacy 2019-11-29 14:46:47
我想在字符串中搜索特定模式。正則表達式類是否提供模式在字符串中的位置(字符串中的索引)?模式的出現次數可能超過1。有實際的例子嗎?
查看完整描述

3 回答

?
智慧大石

TA貢獻1946條經驗 獲得超3個贊

Jean Logeart的特別版答案


public static int[] regExIndex(String pattern, String text, Integer fromIndex){

    Matcher matcher = Pattern.compile(pattern).matcher(text);

    if ( ( fromIndex != null && matcher.find(fromIndex) ) || matcher.find()) {

        return new int[]{matcher.start(), matcher.end()};

    }

    return new int[]{-1, -1};

}


查看完整回答
反對 回復 2019-11-29
?
小怪獸愛吃肉

TA貢獻1852條經驗 獲得超1個贊

import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class RegexMatches

{

    public static void main( String args[] ){


      // String to be scanned to find the pattern.

      String line = "This order was places for QT3000! OK?";

      String pattern = "(.*)(\\d+)(.*)";


      // Create a Pattern object

      Pattern r = Pattern.compile(pattern);


      // Now create matcher object.

      Matcher m = r.matcher(line);

      if (m.find( )) {

         System.out.println("Found value: " + m.group(0) );

         System.out.println("Found value: " + m.group(1) );

         System.out.println("Found value: " + m.group(2) );

      } else {

         System.out.println("NO MATCH");

      }

   }

}

結果


Found value: This order was places for QT3000! OK?

Found value: This order was places for QT300

Found value: 0


查看完整回答
反對 回復 2019-11-29
  • 3 回答
  • 0 關注
  • 861 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號