Home > front end >  Is there a way that i can translate Python regular expression to JavaScript regular expression
Is there a way that i can translate Python regular expression to JavaScript regular expression

Time:08-17

I have been having trouble trying to translate python regular expression to a JavaScript regular expression here is the python code r/^([ab].*\1$ | ^[ab]$/ and this was my JavaScript translation /([^ab]*.\1$) | [^ab]$/gm I have to make it match 'a', 'aa', 'bababbb' and it is not supposed to match 'ab', 'baba'. Thank you so much for your help!

For better Clarification:

I did test my output, and I was still getting false and false when I was supposed to get true and false

Here is a picture of the question here

Here is the solution they gave in python for this question here

I hope that was able to clear up some confusion :) Thank you so much for all your help!

CodePudding user response:

This pattern r/^([ab].*\1$ | ^[ab]$/ does not seems to be a valid Python regex notation.

The question is to match a string made up of the characters a and b, and match strings that begin with the same letter.

For that scenario, you can use:

^([ab])(?:[ab]*\1)?$

The pattern matches:

  • ^ Start of string
  • ([ab]) Capture group 1, match either a or b
  • (?: Non capture group
    • [ab]*\1 Optionally match a or b followed by a backreference \1 to match the same character as in group 1.
  • )? Close the non capture group and make it optional to also just allow a single character in total
  • $ End of string

Regex demo

const regex = /^([ab])(?:[ab]*\1)?$/;
[
  "a",
  "aa",
  "bababbb",
  "ab",
  "baba",
].forEach(s => console.log(`${s} --> ${regex.test(s)}`))

  • Related