regex - 如果不在数字之间,则正则表达式匹配字符
问题描述
我需要匹配一个字符来拆分一个大字符串,比如说-
,但如果它在两位数之间则不需要
在a-b
它应该匹配-
在a-4
它应该匹配-
在3-a
它应该匹配-
在3-4
它不应该匹配
我已经尝试过负前瞻和后视,但我只能想出这个(?<=\D)-(?=\D)|(?<=\d)-(?=\D)|(?<=\D)-(?=\d)
有没有更简单的方法来指定这种模式?
编辑:使用正则表达式条件我认为我可以使用(?(?<=\D)-|-(?=\D))
解决方案
以下将适用于这种情况。确保您选择的 Regex 风格具有条件,否则这将不起作用:
-(?(?=\d)(?<=\D-))
- // match a dash
(? // If
(?=\d) // the next character is a digit
(?<= // then start a lookbehind (assert preceding characters are)
\D- // a non-digit then the dash we matched
) // end lookbehind
) // end conditional
没有任何替代品,因为破折号是唯一捕获的字符。
推荐阅读
- reactjs - Material-ui Select MenuItem不显示
- matlab - MATLAB 的 bvp5c 缺乏“收敛性”
- python - 如何获取 2 列中的列表并创建一个元组,将所有元组放入一个列表中,然后返回该列表?
- ruby-on-rails - 如何在后端使用 Ruby on Rails 访问 post 请求中的嵌套 json 参数
- excel - 显示最小值
- visual-studio-code - 如何在不先按 CTRL-F 的情况下通过 F3 立即搜索突出显示的单词?
- postgresql - AWS AppSync 无法再通过 VTL 解析器访问 Aurora Serverless Postgres 集群
- functional-programming - 方案:for-each / delete 后未删除元素
- mongodb - MongoDB 可过滤动态属性的最佳模式?
- javascript - 如果在javascript中的大括号内有任何带方括号的占位符,我如何将字符串更改为新字符串?