条件正则表达式:仅返回一个组

Sve*_*n S 7 regex

我想要匹配的两种类型的网址:

(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)

如你所见,它已经很好用了.由于各种原因,我需要正则表达式只返回一个匹配组.有没有办法实现这一目标?

Bra*_*raj 5

Java / PHP / Python

使用Negative LookaheadPositive Lookbehind获取索引1处的匹配组。

((?<=\.de\/type1\/)\d+|(?<=\.de\/)(?!type1)[^\.]+)
Run Code Online (Sandbox Code Playgroud)

有两个ORed的正则表达式模式。

第一个正则表达式模式寻找 12345

第二个正则表达式模式寻找category/another-title-oh-yes


注意:

  • 每个正则表达式模式必须与每个URL中的一个完全匹配
  • 结合整个正则表达式的括号内(...|...),并从删除括号[^\.]+\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)

的JavaScript

试试这个,在索引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)