-2

how to write a regular expression to match the below string :

name(abc1) or number(param9) or listget(12jtxgh)

I want to match the string enclosed in brackets only if it is prepended by name or number or listget.

I tried to this : r'((.*?))'

and if my expression looks like below :

(name(foo) & number(bar)) - listget(baz)

then it starts matching (name(foo) also. I want my regex to extract only foo, bar and baz from the above expression as it is appended by name, number, listget.

I have to write regex in this form only #r'regex'

zubug55
  • 729
  • 7
  • 27

2 Answers2

0

In regex brackets are special symbols used for grouping. To match them you have to use an escape character \ like this \(.

For NOT matching a symbol ex. brackets:

[^)]

should be used. Where you don't need the escape character.

For finding an alternative you should use the pipe character | surrounded by brackets. Example:

 (mary|john)

For NOT catching a group in a result match inside the the brackets you should start with ?:

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
0

The following regular expression should do the trick:

(?:listget|name|number)\(([^)]+)\)

You can try a working demo by visiting this link. As others pointed out, parenthesis must be escaped in order to match their literal, otherwise they are being used by the regex for different purposes (like capturing groups).

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
  • 1
    Actually the parenthesis does not have to be escaped inside the brackets: 9.4.3 ERE Special Characters - "The period, left-bracket, backslash, and left-parenthesis shall be special except when used in a bracket expression ..." http://pubs.opengroup.org/onlinepubs/007904875/basedefs/xbd_chap09.html#tag_09_03_03 – Robert Andrzejuk Feb 07 '18 at 16:06