[英]Java Matcher Pattern issue
我正在嘗試提取此字符串路徑/share/attachments/docs/
。 我所有的字符串都以/share/attachments/docs/
開頭
例如: /share/attachments/docs/image2.png
之后的字符數不是靜態的!
我嘗試過
Pattern p = Pattern.compile("^(.*)/share/attachments/docs/(\\d+)$");
Matcher m = p.matcher("/share/attachments/docs/image2.png");
m.find();
String link = m.group(2);
System.out.println("Link #: "+link);
但是我收到異常消息: No match found.
奇怪,因為如果我用這個:
Pattern p = Pattern.compile("^(.*)ABC Results for draw no (\\d+)$");
Matcher m = p.matcher("ABC Results for draw no 2888");
然后就可以了!!!
還有一件事是,在極少數情況下,我的字符串不是以/share/attachments/docs/
開頭,然后我不應該解析任何東西,但這與問題沒有直接關系,但是處理起來會很好。
我收到以下異常:
No match found.
這是因為image2.png
與\\d+
不匹配,因此使用更合適的模式(如.+
假設您要提取image2.png
。
這樣,您的正則表達式將為^(.*)/share/attachments/docs/(.+)$
ABC Results for draw no 2888
^(.*)ABC Results for draw no (\\\\d+)$
的regexp ^(.*)ABC Results for draw no (\\\\d+)$
有效,因為在String
的末尾有幾個連續的數字,而在第一種情況下,您有image2.png
包含字母和數字的image2.png
,這就是找不到匹配項的原因。
一般而言,為避免得到IllegalStateException: No match found
,您需要首先檢查find()
的結果,如果它返回true
則輸入String
匹配:
if (m.find()) {
// The String matches with the pattern
String link = m.group(2);
System.out.println("Draw #: "+link);
} else {
System.out.println("Input value doesn't match with the pattern");
}
正則表達式\\d+
(在字符串文字中表示為\\\\d+
)匹配一個或多個數字 。 您的示例輸入沒有對應的數字運行,因此不匹配。 正則表達式元字符.
匹配任何字符(+/-換行符,取決於正則表達式選項); 看來這可能正是您真正追求的。
另外,當您使用Matcher.find()
時,模式不需要匹配整個字符串,因此無需包含.*
即可匹配前導上下文。 此外, find()
返回一個值 , 該值告訴您是否找到與模式匹配的內容。 通常,您希望使用此返回值,在特定情況下,您可以使用它來拒絕那些罕見的不匹配字符串。
也許這更是您想要的:
Pattern p = Pattern.compile("/share/attachments/docs/(.+)$");
Matcher m = p.matcher("/share/attachments/docs/image2.png");
String link;
if (m.find()) {
link = m.group(1);
System.out.println("Draw #: " + link);
} else {
link = null;
System.out.println("Draw #: (not found)");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.