【问题标题】:Regex that doesn't recognise a pattern无法识别模式的正则表达式
【发布时间】:2022-12-04 22:50:19
【问题描述】:

我想制作一个识别某些模式而某些模式不识别的正则表达式。

_*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?<!_)

我想识别的模式样本:

a100__version_2
_a100__version2

我不想识别的模式示例:

100__version_2
a100__version2_
_100__version_2
a100--version-2

正则表达式适用于所有这些,除了这个:

a100--version-2

所以我不想匹配破折号。

我试过_*[a-zA-Z][a-zA-Z0-9_][^-]*.*(?&lt;!_) 所以问题出在 [^-]

【问题讨论】:

    标签: regex


    【解决方案1】:

    要从正则表达式中排除破折号,您可以在 [^-] 字符类之后使用否定先行断言 (?!-)。这将确保正则表达式不匹配 [^-] 字符类之后的任何破折号。

    这是排除破折号的正则表达式的更新版本:

    [a-zA-Z]a-zA-Z0-9_.*(?<!)

    此正则表达式应匹配您要识别的模式,并排除您不想识别的模式。

    以下是此正则表达式如何工作的一些示例:

    a100__version_2   // matches
    _a100__version2   // matches
    100__version_2    // does not match
    a100__version2_   // does not match
    _100__version_2   // does not match
    a100--version-2   // does not match
    

    【讨论】:

      【解决方案2】:

      你可能会使用

      ^_*[a-zA-Z]w*$(?<!_)
      
      • ^ 字符串开始
      • _*匹配可选的下划线
      • [a-zA-Z] 匹配单个字符 a-zA-Z
      • w*匹配可选的单词字符(或[a-zA-Z0-9_]*
      • $字符串结尾
      • (?&lt;!_) Assert not _ to the left at the end of the string

      Regex demo

      【讨论】:

        猜你喜欢
        • 2013-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-16
        • 1970-01-01
        • 1970-01-01
        • 2019-01-06
        相关资源
        最近更新 更多