java正则 任意,Java正则表达式可解析任意数量的Markdown样式的链接

I'm trying to parse a string for any occurrences of markdown style links, i.e. [text](link). I'm able to get the first of the links in a string, but if I have multiple links I can't access the rest. Here is what I've tried, you can run it on ideone:

Pattern p;

try {

p = Pattern.compile("[^\\[]*\\[(?[^\\]]*)\\]\\((?[^\\)]*)\\)(?:.*)");

} catch (PatternSyntaxException ex) {

System.out.println(ex);

throw(ex);

}

Matcher m1 = p.matcher("Hello");

Matcher m2 = p.matcher("Hello [world](ladies)");

Matcher m3 = p.matcher("Well, [this](that) has [two](too many) keys.");

System.out.println("m1 matches: " + m1.matches()); // false

System.out.println("m2 matches: " + m2.matches()); // true

System.out.println("m3 matches: " + m3.matches()); // true

System.out.println("m2 text: " + m2.group("text")); // world

System.out.println("m2 link: " + m2.group("link")); // ladies

System.out.println("m3 text: " + m3.group("text")); // this

System.out.println("m3 link: " + m3.group("link")); // that

System.out.println("m3 end: " + m3.end()); // 44 - I want 18

System.out.println("m3 count: " + m3.groupCount()); // 2 - I want 4

System.out.println("m3 find: " + m3.find()); // false - I want true

I know I can't have repeating groups, but I figured find would work, however it does not work as I expected it to. How can I modify my approach so that I can parse each link?

解决方案

Can't you go through the matches one by one and do the next match from an index after the previous match? You can use this regex:

\[(?[^\]]*)\]\((?[^\)]*)\)

The method Find() tries to find all matches even if the match is a substring of the entire string. Each call to find gets the next match. Matches() tries to match the entire string and fails if it doesn't match. Use something like this:

while (m.find()) {

String s = m.group(1);

// s now contains "BAR"

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值