python-3.xpython-rensregularexpression

Regular expression to catch a specific term in parentheses and in comma seperated list


I'm trying to catch, using a single regular expression, a specific term, i.e. "aa" in any of the following lines:

  1. (aa)
  2. The anomalous assignment ( aa)
  3. Try to push the handles ( aa,bb) and press on them (aa, bb).

But NOT catch it any of the following lines:

  1. The aa is big
  2. aa,bb are handles
  3. To rescue tyou car call (aaa)
  4. The code is (aabbcc) (aa bb)

The general rules are:

  1. I always know the exact term I'm looking for.

  2. Each line is evaluated separately.

  3. Only catch terms that are in parentheses, alone or in any position in a comma separated list.

  4. The list can be of any length and with or without spaces between the items.

  5. Catch only the terms without the commas or spaces.

I'm using re in python 3

Any ideas?

If i want to catch a single item in parentheses, the following expression works: (?<=()(?:[ ])aaa(?:[ ])(?=))

If I don't care about the parentheses, the following expression works (in most cases): (?<=[( ,])aa(?=[) ,])

But I can't find a way to combine between the two expressions


Solution

  • You can put all the allowed characters in your lookarounds:

    (?:(?<=[(,])|(?<=\( ))aa(?=[),]| \))
    

    See example