Callum A Macleod
Callum A Macleod

Reputation: 165

Multiline Regex bar the last line

Im trying to create a regex that captures the last character before a new line to check if a comma is the last character of the line as you would see in a postal address for validation errors as I want to enforce the inclusion of commas.

eg.

Address Line 1,
Address Line 2,
Address Line 3,
Address Line 4,
Region,
Postcode

The information is to be added through a text area but I can't seem to be able to figure it out as I am not very good with regex. So far I have got:

/\w\n/igm

but this captures all the lines plus any line ending with a special character would pass validation whereas all lines bar the last should end with a comma. Any help with this would be greatly appreciated.

cheers Callum

Upvotes: 0

Views: 54

Answers (2)

user557597
user557597

Reputation:

This will find all the errant lines, then add a comma where needed.

Globally find: ([^,\r\n])(?<!Postcode)(\r?\n|\z)
and replace: $1,$2

Should do the trick.

 # ([^,\r\n])(?<!Postcode)(\r?\n|\z)

 ( [^,\r\n] )         # (1), Last char before linebreak or EOS
 (?<! Postcode )      # Not 'Postcode' behind
 ( \r? \n | \z )      # (2), Linebreak or EOS

Upvotes: 0

anubhava
anubhava

Reputation: 785541

Im trying to create a regex that captures the last character before a new line

You can just use this regex:

/,$/m

RegEx Demo

Upvotes: 1

Related Questions