[英]Java regex pattern issue
我有一個字符串:
bundle://24.0:0/com/keop/temp/Activator.class
從這個字符串中,我需要獲取com/keop/temp/Activator
但是需要以下模式:
Pattern p = Pattern.compile("bundle://.*/(.*)\\.class");
僅返回Activator
。 我的錯誤在哪里?
您的正則表達式使用貪心匹配和.
匹配任何字符(但換行符)。 .*/
讀取所有內容,直到最后一個/
, (.*)\\\\.
匹配直到最后期限的所有內容。 除了懶惰匹配,您可以將要匹配的字符限制為非/
然后再匹配要匹配的字符串。 改成
Pattern p = Pattern.compile("bundle://[^/]*/(.*)\\.class");
樣例代碼:
String str = "bundle://24.0:0/com/keop/temp/Activator.class";
Pattern ptrn = Pattern.compile("bundle://[^/]*/(.*)\\.class");
Matcher matcher = ptrn.matcher(str);
if (matcher.find()) {
System.out.println(matcher.group(1));
示例程序的輸出:
com/keop/temp/Activator
您需要在初始標記.*
加上?
進行非貪婪的比賽。
bundle://.*?/(.*)\\.class
^
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.