moffeltje
moffeltje

Reputation: 4659

Regex with max line length and maximum total characters

I'd love to have a regex with that will allow the following:

A text for which every line has a maximal length, lets say 10, and the total text had a maximum number of total characters (lets say 30).

For example this would be some valid inputs:

1)

1234567890

2)

123456789

1234567890

3)

12
123456

12456

And this would be some invalid inputs:

1)

12345678901

2)

1234567890

1234567890
1234567890

(note that invalid example 2 exceeds the 30 characters limit due to the newlines)

What I have so far is this Regex: ^([^\r\n]{0,10}(\r?\n|$)){5}$ (Test it here)
It almost meets my requirements, except that the maximum input is 5 lines instead of 30 characters. I already put a lot of effort in this regex but now I'm stuck.

What modifications does my Regex need to match 30 characters in total?

Upvotes: 2

Views: 2810

Answers (2)

Peter Paul Kiefer
Peter Paul Kiefer

Reputation: 2124

You need something like an and oprator. "rule1 and rule2". According to another question this is accomplished by using non consuming expressions.

(?=^([^\r\n]{0,10}(\r?\n|$)))[\s\S]{1,30}

I'm not sure, the syntax is correct. But use it as a starting point.

Upvotes: 2

Toto
Toto

Reputation: 91488

Add a look ahead in your regex:

^(?=[\s\S]{1,30}$)([^\r\n]{0,10}(\r?\n|$)){5}$

A perl script:

my $re = qr~^(?=[\s\S]{1,30}$)([^\r\n]{0,10}(\r?\n|$)){5}$~;
my @data = (
'12
123456

12456',
'12345678901');
for my $str(@data) {
    say $str, ' : ',($str =~ $re ? 'OK' : 'KO');
}

Output:

12
123456

12456 : OK
12345678901 : KO

Upvotes: 6

Related Questions