0

i would like to perform regex matching, but exclude from the result the characters used for the matching. consider this sample code

import re
string="15  83(B): D17"
result=re.findall(r'\(.+\)',string)
print(result)

here's what i get: ['(B)']

here's what i'd like to have: ['B']

i'm after a generic solution to exclude pattern characters used to start/end a match from the result, not just a solution for this precise case. for example instead of just ( and ) i could have used more complex patterns to start/end matching, and i still would not want to see them as part of the result.

3 Answers 3

2

You need to use a capturing group for the text you need in output like this:

>>> string="15  83(B): D17"
>>> print re.findall(r'\((.*?)\)', string)
['B']

(.*?) is capturing group to match and capture 0 or more characters, non-greedy

In general you can replace starting ( and ending ) with anything you have as before and after your match.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the reply, it works for this example, but if i wanted to replace '(' with '8' and ')' with '1' to get anything between so: '3(B): D', then it doesn't work? i'm not much skilled with regex as you can see. i would like a start pattern and ending pattern and get everything between, excluding both start /end delimiters. is that not appropriate for regex ?
Use print re.findall(r'8(.*?)1', string) and you will get ['3(B): D']
0

The correct regex is it

r"(?<=\()(.*)(?=\))"

U can change ( and ) for anything

Comments

0

Lookaheads and lookbehinds can be used to assert that characters are present before and after a certain position without including them in a match.

>>> string = "15  83(B): D17"
>>> re.findall(r'(?<=\().+(?=\))', string)
['B']

Here, (?<=\() is a positive lookbehind that asserts that an open parenthesis character comes immediately before this position. (?=\)) is a positive lookahead that asserts that a close parenthesis character comes immediately after.

Search the re module documentation for the terms "lookahead" and "lookbehind" for more information.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.