matthew_obrien
matthew_obrien

Reputation: 77

Python RE match not open bracket then string

I want to match the following pattern using python's re.search:

((not open bracket, then 1-3 spaces) or (the start of the string)) then (characters 1 or E) then (any number of spaces) then (close bracket).

Here is what I have so far:

re.search(r'((^\(\s{1,3})|^)[1tE]\s+\)', text)

want to match examples

text = "  E  )"
text = "1 )"

Dont want to match example

text = "( 1 )

Upvotes: 2

Views: 231

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

Consider the following patterns:

  • (
    • ( not open bracket, then 1-3 spaces) - [^(]\s{1,3}
    • or - |
    • (the start of the string) - ^
  • )
  • (characters 1 or E) - [1E]
  • (any number of spaces) - \s*
  • (close bracket) - \).

Joining all of those into one pattern:

(?:[^(]\s{1,3}|^)[1E]\s*\)

To match the entire string, add anchors, ^ and $:

^(?:[^(]\s{1,3}|^)[1E]\s*\)$

See the regex demo.

The (?:...) is a non-capturing group, use a capturing one if you need to access its value in the future.

You can use a verbose regex notation to make it more readable and maintainable:

re.search(
    r"""
    (?:
        [^(]\s{1,3}  # not open bracket, then 1-3 spaces
        |            # or
        ^            # the start of the string
    )
    [1E]  # characters 1 or E
    \s*   # any number of spaces
    \)    # close bracket
    """,
    text,
    re.VERBOSE
)

Upvotes: 1

Related Questions