为什么这个正则表达式在 Python 中有效,但在 Ruby 中无效:
/(?<!([0-1\b][0-9]|[2][0-3]))/
很高兴听到解释以及如何在 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'
当有冒号且不是时间时。
Ruby 正则表达式引擎不允许在后视中捕获组。
如果需要分组,可以使用非捕获组(?:)
:
[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]))/
Docs: https://raw.githubusercontent.com/kkos/oniguruma/master/doc/RE
(?<!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.
学习自这个答案 https://stackoverflow.com/questions/19947331/issue-with-a-look-behind-regular-expression-ruby.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)