I got all of them to match using this (You'll need to add the case-insensitive flag):

(^[a-z][a-z\'&\(\) ]+\bv\b[a-z&\'\(\) ]+(?:.*?) \[?\d+ \w+ \d{4}\]?)

Regex Demo

Explanation:

  • ( Begin capture group
    • [a-z\'&\(\) ]+ Match one or more of the characters in this group
    • \b Match a word boundary
    • v Match the character 'v' literally
    • \b Match a word boundary
    • [a-z&\'\(\) ]+ Match one or more of the characters in this group
    • (?: Begin non-capturing group
      • .*? Match anything
    • ) End non-capturing group
    • \[?\d+ \w+ \d{4}\]? Match a date, optionally surrounded by brackets
  • ) End capture group
Answer from RevanProdigalKnight on Stack Overflow
🌐
YouTube
youtube.com › codetime
python regex match square brackets - YouTube
Download this code from https://codegive.com Title: Python Regex Tutorial: Matching Square Brackets with Code ExamplesIntroduction:Regular expressions (regex...
Published: January 21, 2024
Views: 27
Discussions

python - Regex string between square brackets only if '.' is within string - Stack Overflow
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 More on stackoverflow.com
🌐 stackoverflow.com
regex - Get the string within brackets in Python - Stack Overflow
2 Regular Expression that return matches specific strings in bracket and return its next and preceding string in brackets · 0 Python Parsing with a Variable Name and Square Brackets More on stackoverflow.com
🌐 stackoverflow.com
regex - Regular Expression to match numbers in square brackets in python - Stack Overflow
2 Python - Regular expressions get numbers between parenthesis · 3 How to check if string contains numbers within square brackets · 1 Regex to return integers in square brackets in a string More on stackoverflow.com
🌐 stackoverflow.com
March 30, 2015
python - Regex for matching square brackets and number - Stack Overflow
2 regex python single step, match in a text only brackets that contains more than two separated numbers · I need a reason why all the salvaged ancient coinage are heavily debased compared to modern coinage · What's the difference between a good thought experiment and a bad one? More on stackoverflow.com
🌐 stackoverflow.com
🌐
YouTube
youtube.com › watch
Mastering RegEx in Python | 4 - Square Bracket Pattern - YouTube
Hello Python enthusiasts! Welcome to episode 4 of 'Mastering RegEx in Python.' Today, we're diving into the world of Square Brackets Patterns in RegEx. This ...
Published: July 30, 2023
🌐
GeeksforGeeks
geeksforgeeks.org › python-extract-substrings-between-brackets
Extract substrings between brackets - Python - GeeksforGeeks
January 11, 2025 - Sometimes, while working with Python strings, we can have a problem in which we have to perform the task of extracting numbers in strings that are enclosed in brackets. Let's discuss the certain ways in which this task can be performed. Method 1: Using regex The way to solve this task is to construc
🌐
Regex Tester
regextester.com › 97589
Match anything enclosed by square brackets. - Regex Tester/Debugger
Regular Expression to Useful for find replace chords in some lyric/chord charts.
Find elsewhere
🌐
Mycrazycoding
mycrazycoding.com › python › py_Regular_Expression_Square_Brackets.php
Square Brackets[] in Regular Expression python
It will print each and every character in the string, which is equal to the specified character inside the square bracket.
🌐
Quora
quora.com › How-do-I-extract-text-within-brackets-in-Python
How to extract text within brackets in Python - Quora
Answer (1 of 5): x here is your string holding value which is (text) , to extract only text without the opening and closing brackets you need to use slicing in the starting integer in slicing we use find function to locate the index number of the opening bracket ; we add 1 to it because we want ...
🌐
Reddit
reddit.com › r/learnpython › regex: match everything inside brackets including other brackets
r/learnpython on Reddit: regex: match everything inside brackets including other brackets
January 25, 2023 -

Hi there,

I'm trying to match the inside of the most "external" brackets i.e. from Sum(x3, (x0, x1, x2)) I'd like to extract Sum(x3, (x0, x1, x2)).

I tried

import re
expr = "Sum(x3, (x0, x1, x2))"
match = re.search("(\((.*?)\))", expr) 
bracket_part = match.group(1)
print(bracket_part)

yet this matches only Sum(x3, (x0, x1, x2). Of course one could simply add a ) yet it would be nice to extract (x) from expression like sin(x).

Do guys have an idea how to tell regex to match up until the very last closing bracket? Thanks a lot in advance!

🌐
freeCodeCamp
freecodecamp.org › news › how-do-i-enable-square-brackets-in-regex
How do I Enable Square Brackets in RegEx?
April 27, 2023 - Negating all Non-Vowels and Spaces with Square Brackets in RegEx · In another instance, if you put in hyphen (-) between two characters inside square brackets, it means range.
Top answer
1 of 3
13

What you need is re.sub. Note that both square brackets and pipes are meta-characters so they need to be escaped.

re.sub(r'\[\[(?:[^\]|]*\|)?([^\]|]*)\]\]', r'\1', line)

The \1 in the replacement string refers to what was matched inside the parentheses, that do not start with ?: (i.e. in any case the text you want to have).

There are two caveats. This allows for only a single pipe between the opening and closing brackets. If there are more than one you would need to specify whether you want everything after the first or everything after the last one. The other caveat is that single ] between opening and closing brackets are not allowed. If that is a problem, there would still be a regex solution but it would be considerably more complicated.

For a full explanation of the pattern:

\[\[        # match two literal [
(?:         # start optional non-capturing subpattern for pre-| text
   [^\]|]   # this looks a bit confusing but it is a negated character class
            # allowing any character except for ] and |
   *        # zero or more of those
   \|       # a literal |
)?          # end of subpattern; make it optional
(           # start of capturing group 1 - the text you want to keep
    [^\]|]* # the same character class as above
)           # end of capturing group
\]\]        # match two literal ]
2 of 3
4

You can use re.sub to just find everything between [[ and ]]and I think it's slightly easier to pass in a lambda function to do the replacement (to take everything from the last '|' onwards)

>>> import re
>>> re.sub(r'\[\[(.*?)\]\]', lambda L: L.group(1).rsplit('|', 1)[-1], line)
'is the combination of the code names for Herbicide Orange (HO) and Agent LNX, one of the herbicides and defoliants used by the U.S. military as part of its herbicidal warfare program, Operation Ranch Hand, during the Vietnam War from 1961 to 1971.'
🌐
Stack Overflow
stackoverflow.com › questions › 32416518 › how-to-use-regular-expression-to-match-square-brackets-of-values-and-store-in-py
regex - How to use regular expression to match square brackets of values and store in python dictionary? - Stack Overflow
I have a data and want to get the results stored in a python dictionary as below: #example mydicdata[key] = values in the brackets #example mydicdata[0] = [""] #example mydicdata[7] = ['0', '1', '2', '3', '4', '5', '6', '7'... ] import re data = "{0=[], 1=[], 2=[], 3=[], 4=[], 5=[], 6=[], 7=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 7
🌐
Reddit
reddit.com › r/learnpython › regex with square brackets giving me an error
r/learnpython on Reddit: Regex with square brackets giving me an error
January 13, 2025 -

I am trying to test if a line contains a string of text that contains an open square bracket, but when I use

headerrx = re.compile('^\[Event ')  

it throws an error:

/filter_pgn.py:22: SyntaxWarning: invalid escape sequence '\['
  headerrx = re.compile('^\[Event ')
re.error: unterminated character set at position 1

Any idea what I'm doing wrong? The text I'm trying to parse will look like:

[Event "name of event"]

🌐
Bomberbot
bomberbot.com › regex › how-do-i-enable-square-brackets-in-regex-an-in-depth-guide
How do I Enable Square Brackets in RegEx? An In-Depth Guide - Bomberbot
April 20, 2024 - Here‘s how you would match an opening square bracket [: ... Remember that when using the regex inside a string literal in programming languages like Java or Python, you need to escape the backslash itself:
Top answer
1 of 3
4

To expand on the explanation of the regex used by Avinash in his answer:

Category:([^\[\]]*) consists of several parts:

  • Category: which matches the text "Category:"
  • (...) is a capture group meaning roughly "the expression inside this group is a block that I want to extract"
  • [^...] is a negated set which means "do not match any characters in this set".
  • \[ and \] match "[" and "]" in the text respectively.
  • * means "match zero or more of the preceding regex defined items"

Where I have used ... to indicate that I removed some characters that were not important for the explanation.

So putting it all together, the regex does this:

Finds "Category:" and then matches any number (including zero) characters after that that are not the excluded characters "[" or "]". When it hits an excluded character it stops and the text matched by the regex inside the (...) part is returned. So the regex does not actually look for "[[" or "]]" as you might expect and so will match even if they are left out. You could force it to look for the double square brackets at the beginning and end by changing it to \[\[Category:([^\[\]]*)\]\].

For the second regex, Category:[^\[\]]*, the capture group (...) is excluded, so Python returns everything matched which includes "Category:".

2 of 3
1

Seems like you want something like this,

>>> str = "[[Category:Political culture]]\n\n          [[Category:Political ideologies]]\n\n"
>>> re.findall(r'Category:([^\[\]]*)', str)
['Political culture', 'Political ideologies']
>>> re.findall(r'Category:[^\[\]]*', str)
['Category:Political culture', 'Category:Political ideologies']

By default re.findall will print only the strings which are matched by the pattern present inside a capturing group. If no capturing group was present, then only the findall function would return the matches in list. So in our case , this Category: matches the string category: and this ([^\[\]]*) would capture any character but not of [ or ] zero or more times. Now the findall function would return the characters which are present inside the group index 1.

Top answer
1 of 2
1

You can match the following regular expression.

^(?P<timestamp>[JFMASOND][a-z]{2} [0123]\d [012]\d(?::[0-5]\d){2}\.\d{6}\b) (?P<levelname>[A-Z]) +(?:[A-Z]+: +)?(?:\[+(?P<source>[A-Za-z]+)\]+)? *(?P<message>.+)

Demo

Notice that I've made the capture group source optional.

Depending on requirements some adjustments may need to be made. I assumed, for example, that the source capture group would contain a single word and if there were non-spaces between the levelname and source (or message) it would be comprised of one or more capital letters followed by a colon, as in the second example ('ERR:'). I've also made assumptions about how rigorous the timestamp format must be specified and which capture groups should be made optional. These were of course just guesses about the specification as they were not spelled out in the question.

The regular expression can be broken down as follows. Note that I have put individual spaces in character classes ([ ]) merely to make them visible to the reader. I've tested this with Python (for which named character classes are written (?P<name>....), but it would work in Ruby as well.

^                     # match beginning of string
(?P<timestamp>        # begin 'timestamp' capture group
  [JFMASOND]          # match a cap letter in the char class
  [a-z]{2}            # match two lowercase letters
  [ ]                 # match a space
  [0123]\d            # match a digit in the char class then any digit
  [ ]                 # match a space
  [012]\d             # match a digit in the char class then any digit
  (?:                 # begin a non-capture group
    :                 # match a colon
    [0-5]\d           # match a digit in the char class then any digit 
  ){2}                # end non-capture group and execute it twice
  \.                  # match a period
  \d{6}               # match 6 digits
  \b                  # match a word boundary
)                     # end timestamp capture group
(?P<levelname>        # begin 'levelname' capture group
  [A-Z])[ ]+          # match a capital letter then >= 1 spaces
)                     # end 'levelname' capture group 
(?:[A-Z]+:[ ]+)?      # optionally match >= 1 capital letters
                      # then >= 1 spaces
(?:                   # begin non-capture group
  \[+                 # match one or more left brackets
  (?P<source>         # begin capture group 'source'
    [A-Za-z]+         # match >= 1 chars in char class
  )                   # end capture group 'source'
  \]+                 # match one or more right brackets
)?                    # end non-capture group and make optional
[ ]*                  # match >= 0 spaces
(?P<message>.+)       # match rest of line and save to capture
                      # group 'message'
2 of 2
1

I think this is what you want

^(?<timestamp>[a-zA-Z]{3} [0-9]{1,2} [0-9]{1,2}\:[0-9]{1,2}\:[0-9]{1,2}\.[0-9]{1,6}) (?<levelname>[A-Z]) ?(ERR:)? ?(\[*(?<source>\w*)\]*) (?<message>.*)

brackets should wrap the source field.