【问题标题】:REGEX: Maximum length and number of occurrences正则表达式:最大长度和出现次数
【发布时间】:2015-02-23 09:52:32
【问题描述】:

我不得不编写一个正则表达式,将输入字符串的最大长度限制为 250 个字符,最多 7 行。这些需要在一个正则表达式中。

另外我会写:

^.{0,250}$ // max length
^([^\r\n]*[\r\n][^\r\n]*){0,6}$ //maximum seven lines

将它们组合使用 (?=..)(?=..) 似乎不适用于https://www.debuggex.com/

有什么方法可以在单个正则表达式中完成吗?

编辑:这是.NET

【问题讨论】:

  • 正则表达式语言差异很大。请指定您正在使用哪种正则表达式方言(即哪种编程语言)。

标签: .net regex


【解决方案1】:

您可以为此使用negative lookahead assertion

(?s)^(?!(?:[^\r\n]*\r?\n){7}).{0,250}$

说明:

(?s)       # Mode modifier: Dot matches newlines
^          # Match start of string
(?!        # Assert that it's impossible to match...
 (?:       # (Start of group):
  [^\r\n]* # Any number of characters except newlines
  \r?\n    # followed by one Windows or Mac/Unix newline
 ){7}      # repeated seven times
)          # End of lookahead assertion
.{0,250}   # Match up to 250 characters of any kind
$          # Match end of string

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-12
    • 1970-01-01
    相关资源
    最近更新 更多