简体   繁体   English

正则表达式以匹配行数和每行字符

[英]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. 我试图确保一个字符串包含0到3行,对于给定的行,它包含0到100个字符。 It would need to be a valid expression for JavaScript and Java. 对于JavaScript和Java,它必须是有效的表达式。 Like many people doing RegEx I'm copying from various spots on the Internet. 就像许多执行RegEx的人一样,我正在从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. 向后工作,我认为^.{0,100}$使我“行包含0到100个字符”,但是尝试将其分组为(^.{0,100}$){0,3}不起作用。

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. 新行字符可能是我的问题的一部分,因此我最终得到了类似.{0,100}(?:\\n.{0,100}){0,2}试图说“ 0至100个字符的行(可选)按0到2个新行实例和0到100个其他字符”,但这也失败了。

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. 我终于使用一个在线测试工具一起摸索了这件事: ^.{0,100}(?:(?:\\r\\n|[\\r\\n]).{0,100}){0,2}$似乎可行。

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? 因此,我的问题是,我是否错过了^.{0,100}(?:(?:\\r\\n|[\\r\\n]).{0,100}){0,2}$任何陷阱米之后? 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() : 如果需要,可以使换行符更加紧凑,如果使用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. 经过更多的思考,我意识到上面的换行符建议将匹配4(或更多)行,只要其中有几行是空的。 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. 再次说明,我还是reg exp的新手,所以如果有错误(可能发生),请告诉我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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