2

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?

moffeltje
  • 4,521
  • 4
  • 33
  • 57
  • i do like regex but this can be done in a programming language in no time without any hassle. – yamm May 19 '15 at 09:06
  • @yamm I would love that, but i'm limited to regex atm – moffeltje May 19 '15 at 09:09
  • `len(text) <= 30 and len(text.splitlines()) <= 5 and all(len(n) <= 10 for n in text.splitlines())` this would be a python expression, which would be True if your criteria mach and False otherwise. – yamm May 19 '15 at 09:25

2 Answers2

6

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
Toto
  • 89,455
  • 62
  • 89
  • 125
2

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.

Community
  • 1
  • 1
Peter Paul Kiefer
  • 2,114
  • 1
  • 11
  • 16
  • You forgot a closing `)`, but unfortunately this doesn't match my valid inputs. – moffeltje May 19 '15 at 09:14
  • You'd have to replace `.` with `[\s\S]` unless `/m` was applied, which usually isn't the case. – Siguza May 19 '15 at 09:15
  • @Siguza You're right. I have to use [\s\S] instead of '.'. moffeltje: Even that you pointed me to the missing ) I did not find it for a while. I Edited the answer. I also removed the second (?= .. , because we want to consume the text now. – Peter Paul Kiefer May 19 '15 at 09:26