Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex string between square brackets only if '.' is within string

I’m trying to detect the text between two square brackets in Python however I only want the result where there is a "." within it.

I currently have [(.*?] as my regex, using the following example:

String To Search:
CASE[Data Source].[Week] = ‘THIS WEEK’

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Result:
Data Source, Week

However I need the whole string as [Data Source].[Week], (square brackets included, only if there is a ‘.’ in the middle of the string). There could also be multiple instances where it matches.

>Solution :

You might write a pattern matching [...] and then repeat 1 or more times a . and again [...]

\[[^][]*](?:\.\[[^][]*])+

Explanation

  • \[[^][]*] Match from [...] using a negated character class
  • (?: Non capture group to repeat as a whole part
    • \.\[[^][]*] Match a dot and again [...]
  • )+ Close the non capture group and repeat 1+ times

See a regex demo.

To get multiple matches, you can use re.findall

import re

pattern = r"\[[^][]*](?:\.\[[^][]*])+"

s = ("CASE[Data Source].[Week] = 'THIS WEEK'\n"
            "CASE[Data Source].[Week] = 'THIS WEEK'")

print(re.findall(pattern, s))

Output

['[Data Source].[Week]', '[Data Source].[Week]']

If you also want the values of between square brackets when there is not dot, you can use an alternation with lookaround assertions:

\[[^][]*](?:\.\[[^][]*])+|(?<=\[)[^][]*(?=])

Explanation

  • \[[^][]*](?:\.\[[^][]*])+ The same as the previous pattern
  • | Or
  • (?<=\[)[^][]*(?=]) Match [...] asserting [ to the left and ] to the right

See another regex demo

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading