我想要匹配的两种类型的网址:
(1) www.test.de/type1/12345/this-is-a-title.html
(2) www.test.de/category/another-title-oh-yes.html
Run Code Online (Sandbox Code Playgroud)
在第一种类型中,我想匹配"12345".在第二种类型中我想匹配"category/another-title-oh-yes".
这是我想出的:
(?:(?:\.de\/type1\/([\d]*)\/)|\.de\/([\S]+)\.html)
Run Code Online (Sandbox Code Playgroud)
这将返回以下内容:
对于类型(1):
Match group 1: 12345
Match group 2:
Run Code Online (Sandbox Code Playgroud)
对于类型(2):
Match group:
Match group 2: category/another-title-oh-yes
Run Code Online (Sandbox Code Playgroud)
如你所见,它已经很好用了.由于各种原因,我需要正则表达式只返回一个匹配组.有没有办法实现这一目标?
使用Negative Lookahead和Positive Lookbehind获取索引1处的匹配组。
((?<=\.de\/type1\/)\d+|(?<=\.de\/)(?!type1)[^\.]+)
Run Code Online (Sandbox Code Playgroud)
有两个ORed的正则表达式模式。
第一个正则表达式模式寻找 12345
第二个正则表达式模式寻找category/another-title-oh-yes。
注意:
结合整个正则表达式的括号内(...|...),并从删除括号[^\.]+和\d+其中:
[^\.]+ find anything until dot is found
\d+ find one or more digits
Run Code Online (Sandbox Code Playgroud)这是regex101的在线演示
输入:
www.test.de/type1/12345/this-is-a-title.html
www.test.de/category/another-title-oh-yes.html
Run Code Online (Sandbox Code Playgroud)
输出:
MATCH 1
1. [18-23] `12345`
MATCH 2
1. [57-86] `category/another-title-oh-yes`
Run Code Online (Sandbox Code Playgroud)
试试这个,在索引2处获得两个匹配的组。
((?:\.de\/type1\/)(\d+)|(?:\.de\/)(?!type1)([^\.]+))
Run Code Online (Sandbox Code Playgroud)
这是regex101的在线演示。
输入:
www.test.de/type1/12345/this-is-a-title.html
www.test.de/category/another-title-oh-yes.html
Run Code Online (Sandbox Code Playgroud)
输出:
MATCH 1
1. `.de/type1/12345`
2. `12345`
MATCH 2
1. `.de/category/another-title-oh-yes`
2. `category/another-title-oh-yes`
Run Code Online (Sandbox Code Playgroud)