Match a specific expression across multiple lines with RegularExpressionValidator

I’m trying to build a regular expression to match the text typed by a user in a multineline input

The text should be on that shape:

Class 1: Exemple1 
Class 2: Exemple2
....

Every line must respect that syntax.

I managed to create the regex for a single line but i can’t find a proper solution to extend it to a multilines version

<asp:RegularExpressionValidator ID="RegularExpressionValidator" runat="server"
 ErrorMessage="This is wrong!" ValidationExpression="^[Class]+s[0-9]+:+s+[a-zA-Z]+$"
ControlToValidate="txtUserInput"></asp:RegularExpressionValidator><br />

Thank you in advance for your help

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You may use

^Class[ t]+[0-9]+:[ t]+w+(?:r?nClass[ t]+[0-9]+:[ t]+w+)*$

Or, if the line breaks may be just CR:

^Class[ t]+[0-9]+:[ t]+w+(?:(?:rn?|n)Class[ t]+[0-9]+:[ t]+w+)*$

Or, a more line break sequence agnostic version (where r?n is replaced with [rn]+, but it may match empty lines in between valid lines):

^Class[ t]+[0-9]+:[ t]+w+(?:[rn]+Class[ t]+[0-9]+:[ t]+w+)*$

See the regex demo

I suggest using [ t] instead of s to match horizontal whitespace (it will work both on server- and client-side) and replace [a-zA-Z] with w that matches letters, digits and underscores, not just letters (since your example contains digits, too).

The main difference is the (?:r?nYOUR_SINGLE_LINE_PATTERN)* part, that matches all subsequent lines in the desired format, if any.

Details

  • ^ – start of string
  • Class – a char sequence
  • [ t]+ – 1 or more tabs or spaces
  • [0-9]+ – 1 or more digits
  • : – a colon
  • [ t]+ – 1 or more tabs or spaces
  • w+ – one or more word chars
  • (?:r?nClass[ t]+[0-9]+:[ t]+w+)* – 0 or more repetitions of an optional CR (vbCr) followed with a required newline char (vbLf) (or, if [rn]+ is used, just one or more CR or/and LF chars, or if (?:rn?|n) is used, a CRLF, CR or LF line break) and the pattern of the first line
  • $ – end of string.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x