0

I am trying to rewrite some Python expression to C++ with usage of std::regex with ECMASynax.

Here is the original expression:

(?P<lower_bound>(?P<lower_bound_prefix>>|>=)?(?P<lower_version>([0-9a-zA-Z_]+(?:[.-][0-9a-zA-Z_]+)*))?(?(lower_bound_prefix)|\+))$

I replaced all name capture groups to unnamed groups. Unfortunately, I can't make the last condition to happen. How can I represent this Python re syntax: ?(lower_bound_prefix) in ECMASynax? I know I can reference groups using \int syntax, but how can I check if group has been defined?

Thanks

Piotr Barejko
  • 608
  • 4
  • 15
  • is this what you currently have? `((>|>=)?(([0-9a-zA-Z_]+(?:[.-][0-9a-zA-Z_]+)*))?(?(\1)|\+))$` ? – David542 Dec 06 '19 at 20:35
  • 2
    This feature does not work in ECMAScript even if the conditional construct were supported: all groups that have not participated in the match are initialized with an empty string, they are never `null`. You should re-consider the pattern logic. – Wiktor Stribiżew Dec 06 '19 at 20:43
  • Please add some test cases to help you re-vamp the pattern. Is [this](https://regex101.com/r/HU9JJ7/1) correct demo? – Wiktor Stribiżew Dec 06 '19 at 20:53
  • Thanks guys the comments. It seems like @David542 provided an answer that I followed. – Piotr Barejko Dec 06 '19 at 23:07

1 Answers1

1

Perhaps this answer is better stated in a comment, but Javasript does not support conditional regex syntax.

Here is a good answer with an example: Javascript conditional regular expression if-then-else (first answer). If you want to post the current regex you have in your javascript/C++ I can help you convert it to use the non-conditional syntax.

David542
  • 104,438
  • 178
  • 489
  • 842
  • Thank you for the answer, yes that link answers my question, seems like I need to rewrite the expression with usage of conditionals `(?(?=regex)then|else)` – Piotr Barejko Dec 06 '19 at 22:50