2

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 )
3
  • 1
    You say "not open bracket" but use \( that matches it, why? Try re.search(r'^(?:[^(]\s{1,3})?[1tE]\s+\)', text), see demo. Commented Oct 16, 2020 at 10:34
  • Should this also match? % E ) Commented Oct 16, 2020 at 10:40
  • Hi, did my solution work for you? Commented Oct 18, 2020 at 19:15

1 Answer 1

1

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
)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.