'Regular Expression that return matches specific strings in bracket and return its next and preceding string in brackets
I need to find the string in brackets that matches some specific string and all values in the string. Right not I am getting values from a position where the string matches.
text = 'This is an sample string which have some information in brackets (info; matchingString, someotherString).'
regex= r"\(*?matchingString.*?\)"
matches = re.findall(regex, text)
From this I am getting result matchingString, someotherString) what I want is to get the string before the matching string as well. The result should be like this: (info; matchingString, someotherString) This regex works if the matching string is in the first string in brackets.
Solution 1:[1]
You can use
\([^()]*?matchingString[^)]*\)
See the regex demo. Due to the [^()]*?
, the match will never overflow across other (...)
substrings.
Regex details:
\(
- a(
char[^()]*?
- zero or more chars other than(
and)
as few as possiblematchingString
- a hardcoded string[^)]*
- zero or more chars other than)
\)
- a)
char.
See the Python demo:
import re
text = 'This is an sample string which have some information in brackets (info; matchingString, someotherString).'
regex= r"\([^()]*?matchingString[^)]*\)"
print( re.findall(regex, text) )
# => ['(info; matchingString, someotherString)']
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Wiktor Stribiżew |