0

I have the following string:

string = "x OPTIONAL() y z(..., ...)"

Where OPTIONAL() is indeed optional, so the string may also be:

string = "x y z(..., ...)"

Using regular expressions, I want to match the string until the first one of these characters is found:

([{;=,

Beware that OPTIONAL() includes one of the characters above, but the search should not stop at OPTIONAL(.

So I would like to have:

x OPTIONAL() y z

Or:

x y z

I'm currently using:

re.search("[ \t\n\r\f\v]*(OPTIONAL\(\))?([^([{;=,]+)", string)

And the match properly stops at:

x y z

when OPTIONAL() is not in the string.

However, with OPTIONAL() in the string, the match stops at:

x OPTIONAL
HBv6
  • 3,459
  • 4
  • 29
  • 43

2 Answers2

1

You can use a lookbehind to match ( only if it is preceded by OPTIONAL.

^(?:[^([{,;=]+|(?<=OPTIONAL)\()+

See demo at regex101

bobble bubble
  • 11,625
  • 2
  • 24
  • 38
1

You may use

^(?:OPTIONAL\(\)|[^([{;=,])+

See the regex demo

Details

  • ^ - start of string
  • (?: - start of a non-capturing group that will match either
    • OPTIONAL\(\) - an OPTIONAL() suibstring
    • | - or
    • [^([{;=,] - a negated character class that matches any char other thasn (, [, {, ;, =, ,
  • )+ - one or more times.
Wiktor Stribiżew
  • 561,645
  • 34
  • 376
  • 476