首页 > 解决方案 > 如果不在数字之间,则正则表达式匹配字符

问题描述

我需要匹配一个字符来拆分一个大字符串,比如说-,但如果它在两位数之间则不需要

a-b它应该匹配-

a-4它应该匹配-

3-a它应该匹配-

3-4它不应该匹配

我已经尝试过负前瞻和后视,但我只能想出这个(?<=\D)-(?=\D)|(?<=\d)-(?=\D)|(?<=\D)-(?=\d)

有没有更简单的方法来指定这种模式?

编辑:使用正则表达式条件我认为我可以使用(?(?<=\D)-|-(?=\D))

标签: regexlanguage-agnosticregex-lookarounds

解决方案


以下将适用于这种情况。确保您选择的 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

没有任何替代品,因为破折号是唯一捕获的字符。


推荐阅读