regex for pairs between commas with newlines Javascript

Viewed 234

I'm trying to validate text in a text area. (I will eventually be using an Angular 9 pattern validator with this regex). Can you help me with the regex?

Text will be 1 to N pairs of alphanumeric characters separated by commas, with new lines at the end of each pair. Spaces before or after each alphanumeric don't matter.

Example data (I don't know how to represent the newline in the blockquotes):

TEST12345, R5045876
EUDONOT1234, EF2345Y
AB345EEI2,FT0123

Here's what I have tried for Regex in RegExr which seems to pass, but I can't seem to get it to work as my pattern string.

[ ]?[a-zAZ0-9](?:,[a-zA-Z0-9])*$

2 Answers

You can use

/^[a-zA-Z0-9]+,[^\S\n]*[a-zA-Z0-9]+(?:\n[a-zA-Z0-9]+,[^\S\n]*[a-zA-Z0-9]+)*$/

See the regex demo.

Details:

  • ^ - start of string
  • [a-zA-Z0-9]+ - one or more alphanumeric chars
  • , - a comma
  • [^\S\n]* - zero or more whitespace chars other than a line feed char
  • [a-zA-Z0-9]+ - one or more alphanumeric chars
  • (?: - start of a non-capturing group matching
    • \n - a newline, line feed char
    • [a-zA-Z0-9]+,[^\S\n]*[a-zA-Z0-9]+ - same as above, a word, comma, optional whitespace other than LF, and a word
  • )* - end of the group, one or more repetitions
  • $ - end of string.

Special thanks to Wiktor, for his help in the comments, and his previous answer in this Angular Pattern answer which reminded me what I had forgotten. :) He really deserves some points for this.

His second regex example in the comment was the perfect answer, and then, since I'm using strings to give the patterns regular names, here's my pattern:

private multilinePairsCommaDelimitedWords = '[a-zA-Z0-9]+,[^\\S\\n]*[a-zA-Z0-9]+(?:\\n[a-zA-Z0-9]+,[^\\S\\n]*[a-zA-Z0-9]+)*';

and the final use of my validator:

this.firstFormGroup = this._formBuilder.group({
  workstations: ['', [Validators.required, Validators.pattern(this.multilinePairsCommaDelimitedWords)] ],
  softDeleteDate: ['', Validators.required]
});
Related