简体   繁体   中英

Regular Expression to Match Number of Lines and Characters per Line

I'm trying to make sure that a string contains between 0 and 3 lines, and that for a given line that is present that it contains 0 to 100 characters. It would need to be a valid expression for JavaScript and Java. Like many people doing RegEx I'm copying from various spots on the Internet.

Working backwards I think ^.{0,100}$ gets me the "line contains 0 to 100 characters", but trying to group that as (^.{0,100}$){0,3} doesn't work.

The new line character is probably part of my problem, so I ended up with something like .{0,100}(?:\\n.{0,100}){0,2} trying to say "a line of 0 to 100 characters optionally followed by 0 to 2 instances of a new line and 0 to 100 more characters", but that also failed.

Up until now I got those expressions from other people. Using an online test tool I finally monkeyed this together: ^.{0,100}(?:(?:\\r\\n|[\\r\\n]).{0,100}){0,2}$ which appears to work.

So, my question is, am I missing any pitfalls in ^.{0,100}(?:(?:\\r\\n|[\\r\\n]).{0,100}){0,2}$ given what I'm after? Furthermore, even if that does work is it the best expression to use?

I think what you have will work fine. You can make the line break part a little more compact if you want, and you don't need ^ and $ if you are using matches() :

String regex = ".{0,100}(?:[\r\n]+.{0,100}){0,2}";

EDIT

After some more thoughts I realized the newline suggestion above will match 4 (or more) lines as long as a couple of them are empty. So, we are back to your suggested example. Oh well, at least the start and end characters can be omitted.

String regex = ".{0,100}(?:(?:\r\n|[\r\n]).{0,100}){0,2}";

I'm not very good at regular expressions but would this work?

^.{0,100}\n?(.{0,100}\n)?.{0,100}?$

Again I'm still new to reg exp, so if there is an error(which is likely) please tell me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM