首页 > 解决方案 > 正则表达式匹配组号

问题描述

我正在学习正则表达式并遇到了问题。我有以下内容:

href="http://google.com/topic/713725-dogs-are-great-3"> href="http://google.com/topic/213225-humans-are-great"> href="http://google.com/topic/342315-cats-are-great-but-small">

使用此代码 href="(?:[^"]*)topic/([^<]*)">

我可以选择

713725-dogs-are-great-3 213225-humans-are-great 342315-cats-are-great-but-small

但我只想匹配数字

342315 213225 713725

有任何想法吗?

标签: regex

解决方案


使用您显示的示例和尝试,请尝试以下正则表达式;这将创建 1 个捕获组,您可以使用它来获取匹配的值。

\bhref="(?:[^"]*)topic\/(\d+)-.*">$

上述正则表达式的在线演示

说明:为上述添加详细说明。

\bhref="          ##Matching href using \b before it as a word boundary followed by =" here.
(?:[^"]*)topic\/  ##In a non-capturing group matching till " everything till topic/
(\d+)             ##Creating 1st capturing group which has digits in it.
-.*">$            ##Matching everything till " followed by "> till end of value.

推荐阅读