I want to extract two path elements from the end of the URL.

Asked 1 years ago, Updated 1 years ago, 58 views

For example,

https://example.com/theater/13/130301/3271/

Represents ISBN from the URL

130301/3271/

I would like to extract as a key.

sre_constants.error:missing), unterminated subpattern at position 1

I get an error like this, but I don't know what to do, so please let me know.

The program is as follows:

import re

url='https://example.com/theater/13/130301/3271/'
m = re.search(r'/(^/([^/])+) $', url)
print(m.group(1))

python regular-expression

2022-09-30 10:44

1 Answers

missing),

This means that the ) that should exist cannot be found (not enough).
The reason is that there are two open brackets (), but there is only one closed bracket and it is not compatible.
If I were to create a group, I think it would be as follows.

import re

url='https://example.com/theater/13/130301/3271/'
m=re.search(r'([^/]+/[^/]+/)$',url)
print(m.group(1))

Output:

130301/3271/

By the way, in this case, you don't have to make a group because the whole match is the result you want.
The group method is considered 0 if you omit the argument, and 0 means the whole match.

m=re.search(r'[^/]+/[^/]+/$',url)
print(m.group())


2022-09-30 10:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.