Sumedha Vangury
Sumedha Vangury

Reputation: 683

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} ")]

Upvotes: 4

Views: 6391

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626835

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. \z is an unambiguous string end anchor.

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

Upvotes: 0

Kerwin
Kerwin

Reputation: 1212

^.*[^,]$

.* means all char,don't need so long

Upvotes: 5

vks
vks

Reputation: 67968

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

                                                                                                        ^^

Just add lookbehind at the end.

Upvotes: 2

Related Questions