简体   繁体   English

正则表达式,用于检查正确的字段数量

[英]Regular Expression for check of correct amount of fields

I have a certain file where the fields are seperated by a comma. 我有一个文件,其中的字段用逗号分隔。

bla,20171206123901,bla,

I want to check if the correct amount of fields is in the line by regular expression where the last comma is optional. 我想通过最后一个逗号为可选的正则表达式检查行中是否包含正确的字段数。 At this example it should be exactly 3. What is the correct regular expression for that? 在此示例中,它应该恰好是3。正确的正则表达式是什么?

I thought that maybe this one could work, but it is not working 我以为也许这个可以用,但是没用

(.*,){3}(,)[0,1]

because this one also matches lines which have too much fields. 因为这一行也匹配字段过多的行。

Any help would be really appreciated 任何帮助将非常感激

Thank you 谢谢

Here is pattern which you can try applying to each line: 这是您可以尝试应用于每一行的模式:

^[^,]*,[^,]*,[^,]*,?$

This assumes that if the optional third comma does appear, that it is the last thing on the line. 假设如果确实出现了可选的第三个逗号,则表示它是最后一行。 Also, the pattern allows for empty columns. 同样,该模式允许空列。 If this is not the case, then replace [^,]* with [^,]+ everywhere in the pattern. 如果不是这种情况,则在模式中的所有位置都将[^,]*替换为[^,]+

Another way to write the above takes advantage of repeated columns: 编写上述内容的另一种方法是利用重复的列:

^(?:[^,]*,){2}[^,]*,?$

Here, you may replace 2 with the number of desired columns minus one . 在这里,您可以将2替换为所需的列数减去一 So for 3 columns, you would use {2} in the pattern. 因此,对于3列,您将在模式中使用{2}

Demo 演示

This one should work: 这应该工作:

^(?:[^,]+,[^,]*){2},?$

and you can change the number (number of columns minus one.) if you need to add more columns. 如果需要添加更多列,则可以更改数量(列数减去一。)。

Test it here. 在这里测试。

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

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