在Python中使用Javascript正则表达式的瘦兼容层
js-regex的Python项目详细描述
js正则表达式
在Python中使用Javascript正则表达式的兼容层。
你知道正则表达式在不同的编程语言中会有所不同吗?
例如,让我们考虑模式"^abc$"
,它与字符串匹配
"abc"
。但是字符串"abc\n"
呢?它在Python中也匹配,
但不是Javascript!在
这和其他一些细微的差异对于跨语言来说是非常重要的
像jsonschema
这样的标准,这就是js-regex
存在的原因。在
工作原理
importreimportjs_regexre.compile("^abc$").search("abc\n")# matches, unlike JSjs_regex.compile("^abc$").search("abc\n")# does not match
在内部,js_regex.compile()
替换了JS regex语法,它具有不同的
在Python中,无论使用Pythonregex语法都具有预期的含义。在
这只适用于.search()
方法-没有等价的
.match()
或{
我们还检查在Python中有效但JS无效的构造,例如
命名捕获组-并引发显式错误。有效的构造
在JS而不是Python中也可能会引发错误,因为我们仍然使用Python的
re.compile()
引擎盖下的功能!在
下表改编自this larger version, 在JS和Python具有相同行为的其他语言和任何行中,都要进行注释。在
Feature | Javascript | Python | Handling |
---|---|---|---|
^{ | no | yes | Converted to JS behaviour |
^{ | yes | no | Converted to JS behaviour |
^{ | ascii | unicode | Converted to JS behaviour (including ^{ |
^{ | at end | allows trailing ^{ | Converted to JS behaviour |
^{ | no | yes | Explicit error, use ^{ |
^{ | no | yes | Explicit error, use ^{ |
^{ | new in ES2018 | yes | Allowed |
^{ | new in ES2018 | yes | Allowed |
^{ | no | yes | Explicit error |
^{ | no | yes | Explicit error |
^{ | no | yes | Explicit error |
^{ | no | yes | Not detected (yet) |
^{ | no | yes | Not detected (yet) |
^{ | new in ES2018 | no | Error from Python, not translated (yet) |
^{ | new in ES2018 | no | Error from Python, not translated (yet) |
^{ | ^{ | yes | Explicit error, compile with ^{ |
^{ | ^{ | yes | Explicit error, compile with ^{ |
^{ | no | yes | Explicit error, compile with ^{ |
^{ | no | yes | Explicit error, there is no corresponding mode in Javascript |
Backreferences non-existent groups are an error | no | yes | Follows Python behaviour |
Backreferences to failed groups also fail | no | yes | Follows Python behaviour |
Nested references ^{ | yes | no | Follows Python behaviour |
请注意,在许多情况下,只有Python的regex特性才会被视为 JS regex引擎的一个普通模式。目前我们提出了一个明确的错误 在这样的输入上,但可能会在将来的版本中转换为JS行为。在
变更日志
1.0.1-2019年10月17日
- 允许在Python2上使用本机字符串。这实际上是无效的 但它只会存在几个月所以不管怎样。在
1.0.0-2019年10月4日
- 现在我们认为这个特性是完整和稳定的,正如所有构造所建议的那样
for
jsonschema
模式受支持,所有Python端不兼容
被检测到。在 - 编译后的模式现在缓存在python3上,与
re.compile
完全一样
0.4.0-2019年10月3日
- 现在兼容Python2.7和3.5,直到
their respective EOL dates。在
0.3.0-2019年9月30日
- 修正了对非尾随
$
的处理,例如在"^abc$|^def$"
中两者都被转换 - 为
re.LOCALE
和re.VERBOSE
标志添加了显式错误,它们没有等效的JS - 添加了使用Python-only regex特性的显式检查和错误
0.2.0-2019年9月28日
jsonschema
模式受支持,所有Python端不兼容
被检测到。在re.compile
完全一样- 现在兼容Python2.7和3.5,直到 their respective EOL dates。在
0.3.0-2019年9月30日
- 修正了对非尾随
$
的处理,例如在"^abc$|^def$"
中两者都被转换 - 为
re.LOCALE
和re.VERBOSE
标志添加了显式错误,它们没有等效的JS - 添加了使用Python-only regex特性的显式检查和错误
0.2.0-2019年9月28日
$
的处理,例如在"^abc$|^def$"
中两者都被转换re.LOCALE
和re.VERBOSE
标志添加了显式错误,它们没有等效的JS尽可能将JS语法转换为Python等效语法。在
0.1.0-2019年9月28日
初始版本,带有项目设置和非常基本的实现。在
- 项目
标签: