【问题标题】:String must be alphanumeric and contain a certain substring字符串必须是字母数字并包含某个子字符串
【发布时间】:2021-09-16 15:13:38
【问题描述】:

我正在添加一个确定给定输入是否有效的正则表达式。输入应该是字母数字(也允许使用下划线、破折号、句点)并且在 1 到 60 个字符之间。它还应该包含一个特定的子字符串(让我们说“foo.bar”)。这是我的尝试:

^.[a-zA-Z0-9_.-]{1,60}$

除了子字符串部分之外,这正是我所需要的。我不确定如何添加“字符串必须包含子字符串 foo.bar”要求。 FWIW 我在 Ruby 中执行此操作,所以我理解这意味着正在使用 PCRE。

例如,这个字符串应该是有效的:

aGreatStringWithfoo.barInIt1111

这不应该

aBadStringWithoutTheSubstringInIt

【问题讨论】:

  • 使用^(?=.*foo\.bar)[a-zA-Z0-9_.-]{1,60}$

标签: regex pcre


【解决方案1】:

使用

^(?=.{1,60}$)[a-zA-Z0-9_.-]*foo\.bar[a-zA-Z0-9_.-]*$

regex proof

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (?=                      look ahead to see if there is:
--------------------------------------------------------------------------------
    .{1,60}                  any character except \n (between 1 and
                             60 times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
    $                        before an optional \n, and the end of
                             the string
--------------------------------------------------------------------------------
  )                        end of look-ahead
--------------------------------------------------------------------------------
  [a-zA-Z0-9_.-]*          any character of: 'a' to 'z', 'A' to 'Z',
                           '0' to '9', '_', '.', '-' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  foo                      'foo'
--------------------------------------------------------------------------------
  \.                       '.'
--------------------------------------------------------------------------------
  bar                      'bar'
--------------------------------------------------------------------------------
  [a-zA-Z0-9_.-]*          any character of: 'a' to 'z', 'A' to 'Z',
                           '0' to '9', '_', '.', '-' (0 or more times
                           (matching the most amount possible))
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

【讨论】:

    猜你喜欢
    • 2019-02-17
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2013-05-27
    • 1970-01-01
    • 2019-08-05
    • 1970-01-01
    • 2019-10-15
    相关资源
    最近更新 更多