我正在尝试提取此字符串路径 /share/attachments/docs/
之后的所有内容。我所有的字符串都以 /share/attachments/docs/
例如:/share/attachments/docs/image2.png
../docs/之后的字符数不是静态的!
我试过
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);
但我得到的异常是:找不到匹配项。
奇怪,因为如果我使用这个:
Pattern p = Pattern.compile("^(.*)ABC Results for draw no (\\d+)$");
Matcher m = p.matcher("ABC Results for draw no 2888");
然后就可以了!!!
还有一件事是,在一些非常罕见的情况下,我的字符串不是以 /share/attachments/docs/
开头,然后我不应该解析任何东西,但这与问题没有直接关系,但处理起来会很好。
最佳答案
I am getting Exception that:
No match found.
这是因为 image2.png
与 \d+
不匹配使用更合适的模式如 .+
假设你想提取image2.png
。
您的正则表达式将是 ^(.*)/share/attachments/docs/(.+)$
在 ABC Results for draw no 2888
的情况下,正则表达式 ^(.*)ABC Results for draw no (\\d+)$
有效,因为您有多个String
末尾的连续数字,而在第一种情况下,您的 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");
}
关于Java 匹配器模式问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39621485/