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

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

將特定模式與范圍匹配的正則表達式

將特定模式與范圍匹配的正則表達式

Helenr 2021-05-10 16:47:50
我想檢查一個字符串是否匹配1-2個字母,1-4個數字和1個字母的模式。(例如:CC44C,C4444C)。我知道這str.matches("^[A-Z]{2}\\d{4}[A-Z]{1}")將完全匹配2個字母,4個數字和1個字母的模式。(例如:CC4444C)但是,如何使它與某個范圍(即1-2個字母,1-4個數字)匹配的模式呢?我已經嘗試過str.matches("^[A-Z]{1-2}\\d{1-4}[A-Z]{1}"),但是它給了我以下錯誤:java.util.regex.PatternSyntaxException: Unclosed counted closure near index 8^[A-Z]{2-3}\d{1-4}[A-Z]{1}
查看完整描述

1 回答

?
搖曳的薔薇

TA貢獻1793條經驗 獲得超6個贊

您需要將{1-2}更改為{1,2},您可以將其理解為{minimun,maximum}。請運行以下示例并查看結果。


public class RegularExpression {


public static void main(String[] ar) {

    String str1 = "CC44C";

    String str2 = "C4444C";

    String str3 = "4444C";

    String str4 = "SDFSD123C";

    String pattern = "^[A-Z]{1,2}\\d{1,4}[A-Z]{1}";

    System.out.println(str1+" matches?: "+str1.matches(pattern));

    System.out.println(str2+" matches?: "+str2.matches(pattern));

    System.out.println(str3+" matches?: "+str3.matches(pattern));

    System.out.println(str4+" matches?: "+str4.matches(pattern));

}

}


此外,如果您不知道最大值,則可以使用{1,}。


    String newPattern = "^[A-Za-z]{1,}\\d{1,}[A-Za-z]{1,}";

您可以將上面的模式更改為newPattern并查看結果。


希望這可以對您有所幫助:)


查看完整回答
反對 回復 2021-05-19
  • 1 回答
  • 0 關注
  • 200 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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