0

I have tested this Regex
(?<=\))(.+?)(?=\()|(?<=\))(.+?)\b|(.+?)(?=\()

but it doesn't work for strings like this pattern (ef)abc(gh).

I got a result like this "(ef)abc".

But these 3 regexes (?<=\))(.+?)(?=\() , (?<=\))(.+?)\b, (.+?)(?=\() do work separately for "(ef)abc(gh)", "(ef)abc" ,"abc(ef)" .

can anyone tell me where the problem is or how can I get the expected result?

Ahosan Karim Asik
  • 3,219
  • 1
  • 18
  • 27
April
  • 819
  • 2
  • 12
  • 23

3 Answers3

0

Assuming you are looking to match the text from between the elements in parenthesis, try this:

^(?:\(\w*\))?([\w]*)(?:\(\w*\))?$

^            - beginning of string
(?:\(\w*\))? - non-capturing group, match 0 or more alphabetic letters within parens, all optional
([\w]*)      - capturing group, match 0 or more alphabetic letters
(?:\(\w*\))? - non-capturing group, match 0 or more alphabetic letters within parens, all optional
$            - end of string

You haven't specified what language you might be using, but here is an example in Python:

>>> import re

>>> string = "(ef)abc(gh)"
>>> string2 = "(ef)abc"
>>> string3 = "abc(gh)"

>>> p = re.compile(r'^(?:\(\w*\))?([\w]*)(?:\(\w*\))?$')

>>> m = re.search(p, string)
>>> m2 = re.search(p, string2)
>>> m3 = re.search(p, string3)

>>> print m.groups()[0]
'abc'
>>> print m2.groups()[0]
'abc'
>>> print m3.groups()[0]
'abc'
Totem
  • 7,189
  • 5
  • 39
  • 66
0
\([^)]+\)|([^()\n]+)

Try this.Just grab the capture or group.See demo.

https://regex101.com/r/tX2bH4/6

vks
  • 67,027
  • 10
  • 91
  • 124
0

Your problem is that (.+?)(?=\() matches "(ef)abc" in "(ef)abc(gh)".

The easiest solution to this problem is be more explicit about what you are looking for. In this case by exchanging "any character" ., with "any character that is not a parenthesis" [^\(\)].

(?<=\))([^\(\)]+?)(?=\()|(?<=\))([^\(\)]+?)\b|([^\(\)]+?)(?=\()

A cleaner regexp would be

(?:(?<=^)|(?<=\)))([^\(\)]+)(?:(?=\()|(?=$))
Taemyr
  • 3,407
  • 16
  • 26