后视模式中的无效模式 [英] Invalid pattern in look-behind
本文介绍了后视模式中的无效模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么这个正则表达式在 Python 中有效,而在 Ruby 中无效:
Why does this regex work in Python but not in Ruby:
/(?<!([0-1\b][0-9]|[2][0-3]))/
很高兴听到解释以及如何在 Ruby 中解决它
Would be great to hear an explanation and also how to get around it in Ruby
使用整行代码进行
re.sub(r'(?<!([0-1\b][0-9]|[2][0-3])):(?!([0-5][0-9])((?i)(am)|(pm)|(a\.m)|(p\.m)|(a\.m\.)|(p\.m\.))?\b)' , ':\n' , s)
基本上,当有冒号但不是时间时,我会尝试添加 '\n'
.
Basically, I'm trying to add '\n'
when there is a colon and it is not a time.
推荐答案
Ruby 正则表达式引擎不允许在后视中捕获组.如果需要分组,可以使用非捕获组 (?:)
:
Ruby regex engine doesn't allow capturing groups in look behinds.
If you need grouping, you can use a non-capturing group (?:)
:
[8] pry(main)> /(?<!(:?[0-1\b][0-9]|[2][0-3]))/
SyntaxError: (eval):2: invalid pattern in look-behind: /(?<!(:?[0-1\b][0-9]|[2][0-3]))/
[8] pry(main)> /(?<!(?:[0-1\b][0-9]|[2][0-3]))/
=> /(?<!(?:[0-1\b][0-9]|[2][0-3]))/
(?<!subexp) negative look-behind
Subexp of look-behind must be fixed-width.
But top-level alternatives can be of various lengths.
ex. (?<=a|bc) is OK. (?<=aaa(?:b|cd)) is not allowed.
In negative look-behind, capturing group isn't allowed,
but non-capturing group (?:) is allowed.
从这个答案中学习.
这篇关于后视模式中的无效模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文