2

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.

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Abdul Muqeet
  • 65
  • 2
  • 8

1 Answers1

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 possible
  • matchingString - 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)']
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • yes, thanks this answers the question. Just one problem arises when I use r"\([^()]*?matchingString[^)]*\)" , this regex breaks if there is a URL at the end of brackets for example: the regex result is match='(version 2.26B, MTI Health Services, http://www.m> but it should be matched like this: (version 2.26B, MTI Health Services, http://www.mtifwb.com) When matching string is MTI Health Services. – Abdul Muqeet Jul 18 '21 at 17:01
  • @AbdulMuqeet No idea what you mean. If you need follow up help, please share a regex101.com fiddle. – Wiktor Stribiżew Jul 18 '21 at 20:08
  • Thankyou so much for your help. Actually I was using about a new regex in which I want to find the one exact string followed by et.al then some digit. For achieving this I created a regex that works for some strings but I am not sure if it works for every string. Can you please correct this? this would be really helpful for me thanks. https://regex101.com/r/hspAND/1 – Abdul Muqeet Jul 19 '21 at 17:52
  • @AbdulMuqeet Sorry, that is not clear to me, see [this regex demo](https://regex101.com/r/hspAND/2). – Wiktor Stribiżew Jul 19 '21 at 21:35