2015-02-23 71 views
1

我不得不寫一個正則表達式,該表達式將輸入字符串限制爲最大長度爲250個字符,最大長度爲7行。這些都需要在一個正則表達式中。REGEX:出現的最大長度和數量

Seperately我會寫:

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

使用結合他們 (= ..?)(= ..?)似乎並不在https://www.debuggex.com/

工作有什麼辦法可以這樣在一個正則表達式中完成?

編輯:這是.NET

+1

正則表達式語言大相徑庭。請指定您正在使用哪種正則表達式(即,哪種編程語言)的方言。 – 2015-02-23 09:54:44

回答

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