Conditional Regexp: return only one group
regex
Solution
Java/PHP/Python
Get both the matched group at index 1 using both Negative Lookahead and Positive Lookbehind.
((?<=\.de\/type1\/)\d+|(?<=\.de\/)(?!type1)[^\.]+)
There are two regex pattern that are ORed.
First regex pattern looks for `12345`
Second regex pattern looks for `category/another-title-oh-yes`.
Note:
- Each regex pattern must match exactly one match in each URL
Combine whole regex pattern inside the parenthesis `(...|...)` and remove parenthesis from the `[^\.]+` and `\d+` where:
[^\.]+ find anything until dot is found
\d+ find one or more digits
Here is online demo on regex101
Input:
www.test.de/type1/12345/this-is-a-title.html
www.test.de/category/another-title-oh-yes.html
Output:
MATCH 1
1. [18-23] `12345`
MATCH 2
1. [57-86] `category/another-title-oh-yes`
JavaScript
try this one and get both the matched group at index 2.
((?:\.de\/type1\/)(\d+)|(?:\.de\/)(?!type1)([^\.]+))
Here is online demo on regex101.
Input:
www.test.de/type1/12345/this-is-a-title.html
www.test.de/category/another-title-oh-yes.html
Output:
MATCH 1
1. `.de/type1/12345`
2. `12345`
MATCH 2
1. `.de/category/another-title-oh-yes`
2. `category/another-title-oh-yes`
Problem
Two types of URLs I want to match: ``` (1) www.test.de/type1/12345/this-is-a-title.html (2) www.test.de/category/another-title-oh-yes.html ``` In the first type, I want to match "12345". In the second type I want to match "category/another-title-oh-yes". Here is what I came up with: ``` (?:(?:\.de\/type1\/([\d]*)\/)|\.de\/([\S]+)\.html) ``` This returns the following: For type (1): ``` Match group 1: 12345 Match group 2: ``` For type (2): ``` Match group: Match group 2: category/another-title-oh-yes ``` As you can see, it is working pretty well already. For various reasons I need the regex to return only one match-group, though. Is there a way to achieve that?