Home > Software design >  How to include a multiline text in regex pattern
How to include a multiline text in regex pattern

Time:08-12

I have a pattern ^[0-9] $, but I want it to include a \n new-line symbol so that the string like below would be valid: 123\n345\n678\n9752\n or in other words:

123
345
678
9752

CodePudding user response:

Assuming you don't want to include leading/trailing newlines, try:

\A[0-9] (?:\n[0-9] )*\Z

See an online demo.


  • \A - Start-string anchor;
  • [0-9] - 1 digits;
  • (?:\n[0-9] )* - Match nested non-capture group 0 times validating a single newline character and 1 digits;
  • \Z - End-string anchor.

Note: As per my comments, ^[0-9] (?:\n[0-9] )*$ would also work with the right flags turned on/off.

  • Related