简体   繁体   English

正则表达式匹配逗号分隔的字符串,在行的末尾没有逗号

[英]Regex to match comma separated string with no comma at the end of the line

I am trying to write a regex that will allow input of all characters on the keyboard(even space) but will restrict the input of comma at the end of the line. 我正在尝试编写一个允许输入键盘上所有字符(甚至是空格)的正则表达式,但会限制在行尾输入逗号。 I have tried do this,that includes all the possible characters,but it still does not give me the correct output: 我试过这样做,包括所有可能的字符,但它仍然没有给我正确的输出:

   [RegularExpression("^([a-zA-Z0-9\t\n ./<>?;:\"'!@#$%^&*()[]{}_+=|\\-]+,)*[a-zA-Z0-9\t\n ./<>?;:\"'!@#$%^&*()[]{}_+=|\\-]+$", ErrorMessage = "Comma is not allowed at the end of {0} ")]
^.*[^,]$

。*意味着所有的char,不需要这么久

^([a-zA-Z0-9\t\n ./<>?;:\"'!@#$%^&*()[]{}_+=|\\-]+,)*[a-zA-Z0-9\t\n ./<>?;:\"'!@#$%^&*()[]{}_+=|\\-]+(?<!,)$

                                                                                                        ^^

Just add lookbehind at the end. 最后添加lookbehind

a regex that will allow input of all characters on the keyboard(even space) but will restrict the input of comma at the end of the line. 一个正则表达式,允许输入键盘上的所有字符(甚至是空格),但会限制在行尾输入逗号。

Mind that you can type much more than what you typed using a keyboard. 请注意,您输入的内容远远超过您使用键盘输入的内容。 Basically, you want to allow any character but a comma at the end of the line . 基本上,你要允许任何字符,但在该的最后一个逗号。

So, 所以,

(?!,).(?=\r\n|\z)

This regex is checking each line (because of the (?=\\r\\n|$) look-ahead), and the (?!,) look-ahead makes sure the last character (that we match using . ) is not a comma. 这个正则表达式检查每一 (因为(?=\\r\\n|$)前瞻),而(?!,)前瞻确保最后一个字符(我们匹配使用. )不是逗号。 \\z is an unambiguous string end anchor. \\z是一个明确的字符串结束锚。

See regex demo 请参阅正则表达式演示

This will work even on a client side. 这甚至可以在客户端使用。

To also get the full line match, you can just add .* at the beginning of the pattern (as we are not using singleline flag, . does not match newline symbols): 要获得完整的行匹配,您只需在模式的开头添加.* (因为我们不使用单行标记, .不匹配换行符号):

.*(?!,).(?=\r\n|\z)

Or (making it faster with an atomic group or an inline multiline option with ^ start of line anchor, but will not work on the client side) 或(使之与原子团或具有内嵌多选项更快^开始行锚,但不会在客户端上工作)

(?>.*)(?!,).(?=\r\n|\z)
(?m)^.*?(?!,).(?=\r\n|\z) // The fastest of the last three

See demo 演示

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

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