简体   繁体   English

有没有办法可以将 Python 正则表达式转换为 JavaScript 正则表达式

[英]Is there a way that i can translate Python regular expression to JavaScript regular expression

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! 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我必须让它匹配'a','aa','bababbb',它不应该匹配'ab','baba'。谢谢非常感谢您的帮助!

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我确实测试了我的output ,当我应该得到真假时,我仍然变得假和假

Here is a picture of the question here这是问题的图片here

Here is the solution they gave in python for this question here这是他们在 python 中针对问题提供的解决方案

I hope that was able to clear up some confusion:) Thank you so much for all your help!我希望这能够消除一些困惑:)非常感谢您的帮助!

This pattern r/^([ab].*\1$ | ^[ab]$/ does not seems to be a valid Python regex notation.此模式r/^([ab].*\1$ | ^[ab]$/似乎不是有效的 Python 正则表达式表示法。

The question is to match a string made up of the characters a and b, and match strings that begin with the same letter.问题是匹配由字符 a 和 b 组成的字符串,并匹配以相同字母开头的字符串。

For that scenario, you can use:对于这种情况,您可以使用:

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

The pattern matches:模式匹配:

  • ^ Start of string ^字符串开头
  • ([ab]) Capture group 1 , match either a or b ([ab])捕获组 1 ,匹配 a 或 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. [ab]*\1可以选择匹配 a 或 b,后跟反向引用\1以匹配与组 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)}`))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM