【问题标题】:Issue matching with regex与正则表达式匹配的问题
【发布时间】:2019-03-02 14:37:42
【问题描述】:

我正在尝试编写一个正则表达式来匹配以下规则:

  1. 单词仅由字母、数字、撇号、连字符和下划线组成

  2. 以字母或撇号开头,后跟字母

  3. 不包含 2 个或多个撇号、下划线或连字符的序列
  4. 以字母、数字或撇号结尾,前面是字母 s 或撇号后面跟 s

到目前为止,我已经构建了一些正则表达式:

我已经建立了规则 2

^[']?[a-zA-Z][a-zA-Z0-9]+

我已经建立了规则 3

(?!.*[-_'][-_'])(?=[a-z])[a-zA-Z0-9]* 

但对于测试字符串abc def''ghi,它匹配ghi 而不是abc

我已经建立了规则 4

.*[a-zA-Z0-9](?:'s)?(?:s')?$

但对于测试字符串test's abc',它不匹配任何内容,但应该匹配test's

我正在为规则 3 和 4 寻找一些关于如何改进我的正则表达式以便它们工作的建议

【问题讨论】:

  • @trincot 在写下规则时出错。现在已经更新了。
  • 规则 3 应该提到下划线?
  • ^(?!.*[-'_]{2})'?[a-z][\w'-]*([a-z]|s')$ 会满足您的要求吗(忽略大小写)?
  • 您是要编写一个匹配每个规则的单个正则表达式,还是每个规则一个不同的正则表达式?
  • @KhauriMcClain 我正在尝试按照规则执行正则表达式,但如果有帮助,我不介意将它们分开

标签: regex


【解决方案1】:
(?:^|\s)\K(?!'')['a-z](?:['_-]?[a-z0-9])+['_-]?(?:(?<!')'s|s'|[a-z])(?=\s|$)

说明:

(?:^|\s)            # non capture group, beginning of line OR space
\K                  # forget all we've seen until this position
(?!'')              # negative lookahead, not two apos.
['a-z]              # apos. or letter
(?:                 # start non capture group
    ['_-]?          # apos, dash or underscore, optional
    [a-z0-9]        # a letter or digit
)+                  # group may appear 1 or more times
['_-]?              # apos, dash or underscore, optional
(?:                 # start non capture group
    (?<!')          # negative lookbehind, make sure we haven't apos before
    's              # apos and s
  |                 # OR
    s'              # s and apos
  |                 # OR
    [a-z]           # a letter
)                   # end group
(?=\s|$)            # lookahead, make sure we have a space or end of line after

Demo

【讨论】:

  • @RavinderSingh13:谢谢
  • 这个正则表达式对于a123's'd 失败,根据规则应该匹配。
  • @PushpeshKumarRajwanshi:很好,已修复。
  • @Toto 我有一个问题。由于 perl 的正则表达式不支持它,是否可以在没有可变长度后视 (?
  • @J.Doolie:你可以使用非捕获组(?:^|\s),更好的是,后面跟着\K,这意味着,忘记这个位置之前存在的所有东西,(?:^|\s)\K['a-z](?:[a-z0-9]['_-]?)+(?:(?&lt;!')'s|s'|[a-z])(?=\s|$)
猜你喜欢
  • 2011-07-17
  • 2017-09-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多