Search code examples
regexmultiline

regular expression for line length and multiline input


I have tried to create a regular expression that would match if the input text has max 3 lines of text, at most 10 characters per line, and characters are all uppercase. So this string should match: "AA\n\nAA"

but this shouldn't "A12c"

I thought this would work: (I enabled multiline in Pattern)

(^[A-Z]{0,10}$){0,3}

but it doesn't, it only matches if the text is jut one-liner.

I cannot understand what is wrong with the expression - isn't the {0,3} quantifier applied correclty?


Solution

  • You forgot to match the line terminator:

    (^[A-Z]{0,10}$\r?\n?){0,3}
    

    should work, assuming that the option for ^ and $ to match start/end-of-line and not start/end-of-string is set.

    If you need the regex to fail if there are more than 3 lines in your string, you can force the regex engine to match the entire string or not at all by surrounding it with \A and \z anchors:

    \A(^[A-Z]{0,10}$\r?\n?){0,3}\z
    

    However, not all regex flavors support these start-of-string/end-of-string anchors.